-5 java spring spring-mvc simpledateformat spring-boot
我有一个等于 的字符串值"202004"
。我怎样才能将它转换为"April, 2020"
Java?
我会用于java.time
这样的任务。
您可以定义两个java.time.format.DateTimeFormatter
实例(一个用于将输入字符串解析为java.time.YearMonth
,另一个用于将获得的字符串格式化YearMonth
为所需格式的字符串)。
定义一个像这样的方法:
public static String convert(String monthInSomeYear, Locale locale) {
// create something that is able to parse such input
DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("uuuuMM");
// then use that formatter in order to create an object of year and month
YearMonth yearMonth = YearMonth.parse(monthInSomeYear, inputParser);
/*
* the output format is different, so create another formatter
* with a different pattern. Please note that you need a Locale
* in order to define the language used for month names in the output.
*/
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(
"MMMM, uuuu",
Locale.ENGLISH
);
// then return the desired format
return yearMonth.format(outputFormatter);
}
Run Code Online (Sandbox Code Playgroud)
然后使用它,例如在main
方法中:
public static void main(String[] args) {
// your example input
String monthInAYear = "202004";
// use the method
String sameMonthInAYear = convert(monthInAYear, Locale.ENGLISH);
// and print the result
System.out.println(sameMonthInAYear);
}
Run Code Online (Sandbox Code Playgroud)
输出将是这样的:
April, 2020
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1027 次 |
最近记录: |