【问题标题】:Date time format in SpringSpring中的日期时间格式
【发布时间】:2021-10-23 23:03:08
【问题描述】:

我想在 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);

但我收到以下错误:

无法在索引 2 处解析文本“2021-08-23T18:26:37.002166200”

请问如何格式化?

【问题讨论】:

  • 你想要String display = formatter.format (localDateTime) 并打印出来。
  • 既然你想格式化并且你的DateTimeFormatter和你的LocalDateTime都有名为format的方法——不要调用名为parse的方法,因为解析是相反的操作。

标签: java spring date datetime


【解决方案1】:

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 代替会产生:

21 年 8 月 24 日,凌晨 4 点 11 分

详情

我无法想象调用LocalDateTime.now() 是正确的做法。该类缺少任何时区或偏移量的概念,因此它不能代表特定的时间点。

要表示时间线上的特定时刻,请使用InstantOffsetDateTimeZonedDateTime

要捕捉特定时区的当前时刻,请使用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 问题。

【讨论】:

  • 好答案!几个 cmets:(1) DateTimeFormatterLocale 敏感的,因此应始终使用 DateTimeFormatter 指定 Locale。 am/pm 标记通常是Locale-sensitive。 (2) 如果您还提到LocalDateTime now(ZoneId) 作为ZonedDateTime.now(ZoneId) 的替代品,这将对新手有用。
  • @ArvindKumarAvinash 关于语言环境的要点。我觉得 OP 可能想要Locale.forLangaugeTag("ro")(根据谷歌翻译的评论中的ziua de azi是罗马尼亚语现在)。
  • @ArvindKumarAvinash 关于#1,我在下面的详细部分中这样做了。对于 tl;dr 部分,我倾向于使用最少的代码来传达基本思想。但在这种情况下,根据您的评论提示,我使用明确的时区和语言环境添加了第二个示例代码。
  • @ArvindKumarAvinash 关于#2,我认为最好建议从不使用LocalDateTime.now。 (a) 我怀疑程序员很少理解这个调用的含义,他们故意省略了区域/偏移的上下文。即使他们确实理解了,养成这样的习惯也可能在某一天导致错误的代码。 (b) 我还没有想到调用LocalDateTime.now 确实有帮助的情况。在我的书中,让懒惰的人更容易生成较短的字符串并不算是“有帮助”。
  • @OleV.V.很好地发现了罗马尼亚语。我添加了时区和语言环境来匹配。谢谢。
【解决方案2】:
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a");
String formattedDate = localDateTime.format(formatter);
System.out.println(formattedDate);

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 2020-11-20
    • 2019-08-10
    • 2017-12-10
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    相关资源
    最近更新 更多