【问题标题】:Java 8 ZonedDateTime format dateJava 8 ZonedDateTime 格式日期
【发布时间】:2020-09-20 05:39:01
【问题描述】:

我正在编写一个代码来获取英国夏令时的当前日期。 我坚持使用以下代码将日期转换为所需格式。

ZoneId zid = ZoneId.of("Europe/London");      
ZonedDateTime lt = ZonedDateTime.now(zid); 


// create a formatter
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
// apply format()
String value = lt.format(formatter);

System.out.println("value ="+value);

我得到的输出为 value =2020-06-01+02:00,根据书面代码,这很好。但我想要格式 01-JUN-20

的输出

我应该使用什么格式化程序来实现这一点? 在 DST 和不在 DST 时,“欧洲/伦敦”也会给出正确的日期吗? 请帮助我解决以上 2 个问题。

【问题讨论】:

标签: java java-time


【解决方案1】:

tl;博士

ZonedDateTime
.now(
    ZoneId.of( "Europe/London" )
)
.format(
    DateTimeFormatter
    .ofPattern( "dd-MMM-uu" )
    .withLocale( Locale.UK )
)
.toUpperCase(
    Locale.UK
)

看到这个code run live at IdeOne.com

01-JUN-20

详情

你问:

'Europe/London' 在 DST 和不在 DST 时会给出正确的日期吗?

是的,您的代码是正确的。将ZoneId 传递给ZonedDateTime.now 确实说明了挂钟时间的任何异常,包括Daylight Saving Time (DST) 的异常。结果是该地区的人们在查看各自墙上的日历和时钟时看到的日期和时间。

您可能会发现在UTC 中看到同一时刻很有趣或有用,与 UTC 的偏移量为零时分秒。通过调用toInstant提取Instant对象。

你说:

但我想要格式为 01-JUN-20 的输出

定义自定义格式模式以匹配您所需的输出。实例化一个DateTimeFormatter 对象。

指定一个Locale 对象以确定人类语言和文化规范在月份名称的命名和缩写方面。

Locale locale = Locale.UK ;  // Or Locale.US, etc.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" ).withLocale( locale ) ;
String output = myZonedDateTime.format( f ) ;

我不知道如何在 DateTimeFormatter 格式模式中强制全部大写。也许DateTimeFormatterBuilder 可能会有所帮助;我不知道。作为一种解决方法,您可以简单地调用String.toUpperCase( Locale )

Locale locale = Locale.US ;  // Or Locale.UK, etc.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uu" ).withLocale( locale ) ;
String output = myZonedDateTime.format( f ).toUpperCase( locale ) ;

提示

  • 我建议您不要对这样的格式进行硬编码。通常最好通过调用DateTimeFormatter.ofLocalizedDateTimejava.time 为您自动本地化。
  • 我进一步建议避免只使用两位数字表示年份,因为这会使输出更难阅读并产生歧义。节省几个像素或碳粉颗粒并不能证明我在企业中看到的混乱是合理的。
  • 考虑使用标准的ISO 8601 日期格式,如果您的用户可以接受:YYYY-MM-DD。这种格式易于识别,易于心理处理(大中小细节),并且易于跨文化阅读。 java.time 类在生成/解析文本时默认使用 ISO 8601 格式。

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 2020-11-27
    • 2019-07-16
    • 1970-01-01
    • 2016-09-12
    • 2021-09-04
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多