Java 8 ZonedDateTime 格式化日期

Java 8 ZonedDateTime format date

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

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);

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

我应该使用什么格式化程序来实现这一点? 'Europe/London' 在 DST 期间和不在 DST 期间也会给出正确的日期吗? 请帮我解决以上2个问题。

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

详情

你问过:

will 'Europe/London' give proper date while in DST & also while not in DST?

是的,您的代码是正确的。传递一个ZoneId to ZonedDateTime.now does account for any anomalies in wall-clock time, including the anomaly of Daylight Saving Time (DST)。结果是该地区的人们在查看各自墙上的日历和时钟时看到的日期和时间。

您可能会发现在 UTC, an offset from UTC of zero hours-minutes-seconds. Extract a Instant object by calling toInstant 中看到同一时刻很有趣或有用。

你说:

But I want output of format 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 might help; I don't know. As a workaround, you could simply call 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 ) ;

提示

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