问题
This question already has answers here:
ISO 8601 String to Date/Time object in Android
(4 answers)
Closed last year.
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
2011-09-28T21:48:25Z
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.
回答1:
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()) ;
回答2:
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 );
来源:https://stackoverflow.com/questions/7604237/jersey-has-written-my-mysql-timestamp-as-2011-09-28t214825z-how-do-i-format-it