2

I have a mysql backend that has a timestamp field that is auto set as currenttimestamp like so (date_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP). After reading the value as Date, Jersey sends out an xml where the timestamp shows as

<timestamp>2011-09-28T21:48:25Z</timestamp>

Please don't make too much of the backstory: I can't change what I get from Jersey. Now my question is this: how do I parse the 2011-09-28T21:48:25Z from xml as a date that Java understands?

Thanks.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
tribal
  • 653
  • 2
  • 13
  • 26

2 Answers2

1

tl;dr

Instant.parse( "2011-09-28T21:48:25Z" ) 

ISO 8601

Your input string is in standard ISO 8601 format.

Jersey is irrelevant, except that its designers wisely chose to use ISO 8601 formats for serializing date-time values as strings.

java.time

The java.time classes built into Java use ISO 8601 formats by default when parsing/generating Strings. So no need to specify a formatting pattern.

UTC

The Z on the end is short for Zulu and means UTC (GMT).

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.parse( "2011-09-28T21:48:25Z" );

Time Zone

Adjust that Instant into any time zone you desire.

Specify a proper time zone name. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );  // Or "Asia/Kolkata" etc.
ZonedDateTime zdt = instant.atZone( z );

Strings

Do not conflate date-time values with Strings that represent such values.

You can ask the java.time objects to generate a String in any format you desire. But generally best to let the DateTimeFormatter automatically localize for you.

Locale l = Locale.CANADA_FRENCH;  // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

First,

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") ;
df.setTimeZone(TimeZone.getTimeZone("Zulu")) ;
Date dd = df.parse("2011-09-28T21:48:25Z") ;

...then, optionally,

Timestamp ts = new Timestamp(dd.getTime()) ;
mazaneicha
  • 8,794
  • 4
  • 33
  • 52