Java DateFormat月到大写
如何将日期格式化为以下视图2018年10月21日(大写月份)?我可以通过Java DateFormat月到大写,java,simpledateformat,date-format,date-formatting,uppercase,Java,Simpledateformat,Date Format,Date Formatting,Uppercase,如何将日期格式化为以下视图2018年10月21日(大写月份)?我可以通过“%1$TB%1$te,%1$tY”模式获得它,但我需要通过SimpleDataFormat来实现。你能告诉我怎么做吗?你可以这样做: SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH); String dateStr = sdf.format(new Date()); System.out.println( dateStr
“%1$TB%1$te,%1$tY”模式获得它,但我需要通过SimpleDataFormat来实现。你能告诉我怎么做吗?你可以这样做:
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
String dateStr = sdf.format(new Date());
System.out.println( dateStr.toUpperCase() );
简要说明:
首先,我们创建SimpleDataFormat的一个实例,并将默认的“MMMM dd,yyyy”作为参数传递,这将导致“Month day,year”
然后我们将当前日期(newdate()
或您的日期)传递给SimpleDataFormat类以进行转换
最后,我们使用toUpperCase()
使文本为大写
我希望我帮了忙!:D < /P> < P> <代码> SimpleDateFormat <代码>不能给你(虽然你可能会考虑是否可以开发一个子类,可以)。但是现代java日期和时间APIjava.time
,可以:
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);
Map monthNames=Arrays.stream(Month.values())
.collect(Collectors.toMap(m->Long.valueOf(m.getValue()),Month::toString));
DateTimeFormatter dateFormatter=新的DateTimeFormatterBuilder()
.appendText(ChronoField.MONTH\u OF_YEAR,monthNames)
.附录模式(“d,UUU”)
.toFormatter();
LocalDate日期=LocalDate.of(2018年10月21日);
字符串formattedDate=date.format(dateFormatter);
System.out.println(格式化日期);
此代码段的输出符合您的要求:
2018年10月21日
我以为你只需要英文的。对于其他语言,您只需以不同的方式填充地图
这也是因为您无论如何都不想使用SimpleDateFormat
。那个阶级不仅早已过时,而且以麻烦著称<代码>java.time
通常更适合使用
链接:解释如何使用
java.time
我建议您避免使用SimpleDataFormat
类。它不仅早已过时,而且还出了名的麻烦。今天我们有了更好的答案。有没有有用的答案?我对toUpperCase()和toLowerCase()有一种奇怪的不安全感。如果出于某种原因,您的代码曾在4月份以土耳其语作为默认语言的计算机上运行,您将得到:2018年4月21日。注意大写字母I上的点。我总是像dateStr.toUpperCase(Locale.ROOT)那样称呼它们