![](/img/trans.png)
[英]Converting Java ZonedDateTime to a different format 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);
我将 output 的值设为 =2020-06-01+02:00,根据书面代码,这很好。 但我想要格式为01-JUN-20 的output
我应该使用什么格式化程序来实现这一点? 在 DST 和不在 DST 时,“欧洲/伦敦”也会给出正确的日期吗? 请帮助我解决以上两个问题。
ZonedDateTime
.now(
ZoneId.of( "Europe/London" )
)
.format(
DateTimeFormatter
.ofPattern( "dd-MMM-uu" )
.withLocale( Locale.UK )
)
.toUpperCase(
Locale.UK
)
01-JUN-20
您问:
“欧洲/伦敦”会在 DST 和不在 DST 时给出正确的日期吗?
是的,您的代码是正确的。 将ZonedDateTime.now
ZoneId
说明了挂钟时间的任何异常,包括夏令时 (DST)的异常。 结果是该地区的人们在查看各自墙上的日历和时钟时看到的日期和时间。
您可能会发现在UTC 中看到同一时刻很有趣或有用,它与 UTC的偏移量为零时分秒。 通过调用toInstant
提取Instant
object。
你说:
但我想要格式为 01-JUN-20 的 output
定义自定义格式模式以匹配您所需的 output。 实例化一个DateTimeFormatter
object。
指定一个Locale
object 以确定人类语言和文化规范在命名和缩写月份名称。
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.ofLocalizedDateTime
为您自动本地化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.