Spring 中的日期时间格式
我想在 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);
但我收到以下错误:
请问怎么格式化啊
回答
tl;博士
ZonedDateTime
.now()
.format(
DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" )
)
或者,最好是明确的而不是隐含地依赖默认值。也许更好地自动本地化。
ZonedDateTime
.now()
.format(
DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" )
)
查看此代码在 IdeOne.com 上实时运行。
使用Locale.US代替产生:
细节
我无法想象打电话LocalDateTime.now()是正确做法的场景。该类没有任何时区或偏移量的概念,因此它不能代表特定的时刻。
为了表示一个时刻,在时间线上的特定点,使用Instant,OffsetDateTime或ZonedDateTime。
要捕获在特定时区中看到的当前时刻,请使用ZonedDateTime。
ZoneId z = ZoneId.systemDefault() ; // Or specify a zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
让java.time自动为您本地化。
ZonedDateTime
.now(
ZoneId.of( "Europe/Bucharest" )
)
.format(
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale(
new Locale( "ro" , "RO" ) // Romanian in Romania.
)
)
或者您可以对特定格式进行硬编码。不要使用问题中看到的成对的斜杠字符。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu h:mm a" ) ;
我在您的问题或代码中没有看到任何关于Spring 的具体内容。这些是一般的 Java 问题。