Der*_*har 24 java formatting timezone datetime jsr310
如何javax.time.Instant
在本地时区中将a 格式化为字符串?以下内容将本地转换Instant
为UTC,而不是像我期望的那样转换为本地时区.删除呼叫toLocalDateTime()
也是如此.我怎样才能获得当地时间?
public String getDateTimeString( final Instant instant )
{
checkNotNull( instant );
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeFormatter formatter = builder.appendPattern( "yyyyMMddHHmmss" ).toFormatter();
return formatter.print( ZonedDateTime.ofInstant( instant, TimeZone.UTC ).toLocalDateTime() );
}
Run Code Online (Sandbox Code Playgroud)
Jod*_*hen 37
回答这个问题几乎完成了JDK1.8版本
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault());
return formatter.format(instant);
Run Code Online (Sandbox Code Playgroud)
关键是Instant
没有任何时区信息.因此,不能使用任何基于日期/时间字段的模式格式化它,例如"yyyyMMddHHmmss".通过指定区域,DateTimeFormatter
在格式化过程中将瞬间转换为指定的时区,从而可以正确输出.
另一种方法是转换为ZonedDateTime
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return formatter.format(ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()));
Run Code Online (Sandbox Code Playgroud)
两种方法都是等价的,但是如果我的数据对象是一个,我通常会选择第一种方法Instant
.
你为什么期望它使用当地时区?您明确要求UTC:
ZonedDateTime.ofInstant(instant, TimeZone.UTC)
Run Code Online (Sandbox Code Playgroud)
只需指定您当地的时区:
ZonedDateTime.ofInstant(instant, TimeZone.getDefault())
Run Code Online (Sandbox Code Playgroud)
问题是关于JSR-310 参考实现的0.6.3版本,早在 Java 8 和新的日期库到来之前
我放弃了 JSR-310 类DateTimeFormatter
,ZonedDateTime
转而采用老式的java.util.Date
和java.text.SimpleDateFormat
:
public String getDateTimeString( final Instant instant )
{
checkNotNull( instant );
DateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" );
Date date = new Date( instant.toEpochMillisLong() );
return format.format( date );
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20432 次 |
最近记录: |