我正在以这种格式获取字符串,如下所示
03-12-2018
我想根据Java 8标准将其转换为以下格式,请指教
December 03 , 2018
我试过的内容如下所示,但我没有成功,请告知如何实现相同目标
SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);
DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter monthFirst = DateTimeFormatter
.ofLocalizedDate(FormatStyle.LONG)
.withLocale(Locale.ENGLISH);
String actualDate = "03-12-2018";
LocalDate date = LocalDate.parse(actualDate, originalFormatter);
String monthName = date.format(monthFirst);
System.out.println("Month :" + monthName);
输出:
月份:2018年12月3日
既然你使用的是Java 8(即使你没有使用它),也要避免长期过时且臭名昭着的SimpleDateFormat
类。使用内置格式,而不是自己滚动。
你解析了一个03-12-2018
字符串,格式为yyyy-MM-dd
。因此,这将解析到公元3年第12个月的第2018天(2015年前)。很明显12月没有2018天。所以期待一个例外是公平的。这只是SimpleDateFormat
很麻烦的地方之一:标准设置它只是计算几天到几个月和几年,最后是6月9日9,即5年半之后。接下来,您使用包含月份名称和年份的格式化程序格式化此日期,您似乎忘记了月份的某一天。无论如何它打印为Jun 0009
(你应该在你的问题中告诉我们,以便我们可以看到错误;这些信息对于解决你的问题非常有帮助)。
Oracle tutorial: Date Time解释如何使用java.time
。
这只是选择正确格式(并应用正确的Locale
)的问题:
DateTimeFormatter f = DateTimeFormatter.ofPattern("LLLL dd, yyyy");
System.out.println(f.format(yourDate));
顺便说一下,它在the documentation:
...数字/文本:如果模式字母的数量为3或更大,请使用上面的文本规则。否则使用上面的数字规则。 ...
使用以下代码:
SimpleDateFormat month_date = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String actualDate = "03-12-2018";
Date date = sdf.parse(actualDate);
String month_name = month_date.format(date);
System.out.println("Month :" + month_name);