我想在 Spring 中获取当前日期和时间并对其进行格式化。我使用 LocalDateTime 来获取当前日期,但它是这样的:2021-08-23T18:24:36.229362200
并希望以这种格式获取它:"MM/dd/yyyy h:mm a
"
我试过这个:
LocalDateTime localDateTime = LocalDateTime.now(); //ziua de azi
String d = localDateTime.toString();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM//dd//yyyy h:mm a");
localDateTime = LocalDateTime.parse(d, formatter);
但我收到以下错误:
Text '2021-08-23T18:26:37.002166200' could not be parsed at index 2
请问如何格式化?
最佳答案
tl;博士
ZonedDateTime
.now()
.format(
DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" )
)
或者,最好是明确的而不是隐含地依赖默认值。自动本地化也许更好。
ZonedDateTime
.now(
ZoneId.of( "Europe/Bucharest" )
)
.format(
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale(
new Locale( "ro" , "RO" ) // Romanian in Romania.
)
)
查看 code run live at IdeOne.com .
24.08.2021, 04:09
使用 Locale.US
会产生:
8/24/21, 4:11 AM
详情
我无法想象调用 LocalDateTime.now()
是正确的做法。该类缺少任何时区或偏移量的概念,因此它不能代表特定的时间点。
要表示时刻,时间线上的特定点,请使用 Instant
、OffsetDateTime
或 ZonedDateTime
。
要捕捉特定时区的当前时刻,请使用 ZonedDateTime
。
ZoneId z = ZoneId.systemDefault() ; // Or specify a zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
让java.time为你自动本地化。
Locale locale = new Locale( "ro" , "RO" ) ; // For Romanian in Romania. Or `Locale.US`, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatSyle.SHORT ).withLocale( locale );
String output = zdt.format( f ) ;
或者您可以硬编码特定格式。不要使用问题中看到的成对的斜线字符。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" ) ;
我在您的问题或代码中没有看到任何关于 Spring 的具体内容。这些是一般的 Java 问题。
关于java - Spring中的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68895251/