问题描述
如何格式化作为本地时区的字符串?以下将本地 Instant
转换为 ,而不是我所期望的当地时区。将呼叫删除到也是一样的。如何获取当地时间?
How do I format a javax.time.Instant
as a string in the local time zone? The following translates a local Instant
to UTC, not to the local time zone as I was expecting. Removing the call to toLocalDateTime()
does the same. How can I get the local time instead?
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() );
}
注意:我们使用的是旧版本的参考实施。
Note: We're using the older version 0.6.3 of the JSR-310 reference implementation.
推荐答案
在您投票之前,我的回答请注意,问题明确(和粗体字)是指旧版本> 0.6.3 的JSR-310参考实现!我在2012年12月问到这个问题,早在Java 8和新的日期库到来之前!
Before you down vote my answer, please note that the question explicitly (and in bold typeface) refers to old version 0.6.3 of the JSR-310 reference implementation! I asked this question in December 2012, long before the arrival of Java 8 and the new date library!
我放弃了JSR-310课程 DateTimeFormatter
和 ZonedDateTime
而不是使用旧式的 java.util.Date
和 java.text.SimpleDateFormat
:
I gave up on JSR-310 classes DateTimeFormatter
and ZonedDateTime
and instead resorted to old fashioned java.util.Date
and 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 );
}
这篇关于如何在本地时区中将javax.time.Instant格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!