Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a javax.time.Instant as a string in the local time zone?

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.

like image 618
Derek Mahar Avatar asked Dec 06 '12 20:12

Derek Mahar


People also ask

How do you convert instant to string?

withZone(ZoneId. systemDefault()); Instant instant = Instant. parse("2022-02-15T18:35:24.00Z"); String formattedInstant = formatter. format(instant); assertThat(formattedInstant).

How do I convert dateTime to string in Java?

DateTimeFormatter f = DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime. from(f. parse("2012-01-10 23:13:26"));

Does Java instant have timezone?

Instant: java. time. Instant is the class encapsulating the time elapsed from the standard Java epoch(beginning of time in Java) of 1970-01-01T00:00:00Z. Instant instances do have a time zone associated with them – UTC to be specific.

How do you format time in Java?

Solution: This example formats the time by using SimpleDateFormat("HH-mm-ss a") constructor and sdf. format(date) method of SimpleDateFormat class.


1 Answers

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.

like image 154
JodaStephen Avatar answered Sep 24 '22 08:09

JodaStephen