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 expec
Try this:
String dateTime = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(
ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
);
This gives:
2014-08-25T21:52:07-07:00[America/Los_Angeles]
You can change the format by using something other than DateTimeFormatter.ISO_ZONED_DATE_TIME
as the formatter. DateTimeFormatter has a bunch of predefined formatters, or you can define your own.
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!
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 );
}
Answering this question wrt the nearly finished JDK1.8 version
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault());
return formatter.format(instant);
The key is that Instant
does not have any time-zone information. Thus it cannot be formatted using any pattens based on date/time fields, such as "yyyyMMddHHmmss". By specifying the zone in the DateTimeFormatter
, the instant is converted to the specified time-zone during formatting, allowing it to be correctly output.
An alternative approach is to convert to ZonedDateTime
:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return formatter.format(ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()));
Both approaches are equivalent, however I would generally choose the first if my data object was an Instant
.
Why would you expect it to use the local time zone? You're explicitly asking for UTC:
ZonedDateTime.ofInstant(instant, TimeZone.UTC)
Just specify your local time zone instead:
ZonedDateTime.ofInstant(instant, TimeZone.getDefault())