如何将日期格式设置为以下视图(2018年10月21日,大写的月份)?我可以通过"%1$TB %1$te, %1$tY"
模式来获得它,但是我需要通过SimpleDateFormat来实现。你能建议我怎么做吗?
答案 0 :(得分:1)
您可以执行以下操作:
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
String dateStr = sdf.format(new Date());
System.out.println( dateStr.toUpperCase() );
简要说明:
首先,我们创建一个 SimpleDateFormat 实例,并将默认的“ MMMM dd,yyyy”作为参数传递,该结果将产生“ Month day,year”。
然后,我们将当前日期(new Date ()
或您的日期)传递给类 SimpleDateFormat 进行转换。
最后,我们使用toUpperCase()
,使文本为大写。
我希望我有所帮助! :D
答案 1 :(得分:1)
SimpleDateFormat
不能给您(尽管您可能会考虑是否可以开发可以的子类)。但是java.time
(现代的Java日期和时间API)可以:
Map<Long, String> monthNames = Arrays.stream(Month.values())
.collect(Collectors.toMap(m -> Long.valueOf(m.getValue()), Month::toString));
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.MONTH_OF_YEAR, monthNames)
.appendPattern(" d, uuuu")
.toFormatter();
LocalDate date = LocalDate.of(2018, Month.OCTOBER, 21);
String formattedDate = date.format(dateFormatter);
System.out.println(formattedDate);
此代码段的输出是您所要求的:
2018年10月21日
我假设您仅需要英语。对于其他语言,您只需要以不同的方式填充地图即可。
这同样好,因为您仍然不希望使用SimpleDateFormat
。该课程不仅早已过时,而且还因麻烦而闻名。 java.time
通常更好用。
链接: Oracle tutorial: Date Time解释了如何使用java.time
。