我正在写一段代码,以获得英国夏季时间的最新日期。我被困在转换日期以期望的格式使用下面的代码。
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的输出。
我应该用什么格式化程序来达到这个目的呢?另外,“欧洲/伦敦”在DST期间也会给出适当的日期吗?请帮我回答以上两个问题。
发布于 2020-06-01 22:44:43
tl;dr
ZonedDateTime
.now(
ZoneId.of( "Europe/London" )
)
.format(
DateTimeFormatter
.ofPattern( "dd-MMM-uu" )
.withLocale( Locale.UK )
)
.toUpperCase(
Locale.UK
)01-6月20日
详细信息
你问:
“欧洲/伦敦”在DST期间会给出适当的日期吗?
是的,你的代码是正确的。将ZoneId传递给ZonedDateTime.now确实说明了任何时间上的异常,包括夏令时(DST)的异常。其结果是一个日期和时间,在该地区的人们看到时,他们看到日历&时钟在他们各自的墙上。
你可能会发现,在UTC中看到同样的时刻是很有趣或有用的,这与协调世界时的零小时-分-秒相抵消。通过调用Instant来提取toInstant对象。
你说过:
但我想要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.ofLocalizedDateTime为您自动本地化。https://stackoverflow.com/questions/62140379
复制相似问题