Reputation: 28386
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.
Upvotes: 27
Views: 25759
Reputation: 28386
The question was about version 0.6.3 of the JSR-310 reference implementation, 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 );
}
Upvotes: 1
Reputation: 9220
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.
Upvotes: 1
Reputation: 63385
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
.
Upvotes: 41
Reputation: 1500525
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())
Upvotes: 6