Issue
I'm receiving this timestamp in a json body:
{
"timestamp": "2019-03-27 10:04:01.446937+01"
}
And I would like to convert this timestamp into europe/brussels timezone.
I'm using com.fasterxml.jackson.core so I'm wondering if this is possible with annotations in this class for example.
public class MyClass {
@JsonFormat(...)
Date timestamp;
}
If not how can this be achieved using plain java code?
Solution
ISO 8601
If possible, educate the publisher of your data about using standard ISO 8601 formats when exchanging date-time values textually. That means:
- Using a
T
in the middle instead of a SPACE character. - Using hours with minutes in the offset, delimited by a COLON character, rather than abbreviating.
DateTimeFormatter
If switching to ISO 8601 is not possible, define a formatting pattern to match your input.
String input = "2019-03-27 10:04:01.446937+01" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss.SSSSSSx" ) ;
java.time.OffsetDateTime
Parse as an OffsetDateTime
.
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;
odt.toString(): 2019-03-27T10:04:01.446937+01:00
ZonedDateTime
Apply your desired time zone.
ZoneId z = ZoneId.of( "Europe/Brussels" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See this code run at Ideone.com.
zdt.toString(): 2019-03-27T10:04:01.446937+01:00[Europe/Brussels]
In this particular case, Brussels time is already using an offset of one hour ahead of UTC. So no change for the time-of-day from our original.
Answered By - Basil Bourque
Answer Checked By - Cary Denson (JavaFixing Admin)