Date format: \"yyyy-MM-dd\'T\'HH:mm:ss.SSSZ\"
Input date: \"2017-09-18T03:08:20.888+0200\"
Problem: I need retrieve timezon
TimeZone.getTimeZone( // Convert from modern java.time type (`ZoneOffset`/`ZoneId`) to legacy type (`TimeZone`)
OffsetDateTime.parse ( // Instantiate a `OffsetDateTime`, a moment on the timeline.
"2017-09-18T03:08:20.888+0200" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" )
).getOffset() // Extract a `ZoneOffset`, which is a subclass of `ZoneId`.
)
ZoneOffset to legacy TimeZoneThe code seen here is similar to Answers by Yan Khonski, but using the variation of TimeZone.getTimeZone that directly converts from the modern java.time classes (ZoneOffset & ZoneID) to the legacy TimeZone class.
While there is no difference in the end result, this approach uses a an explicit conversion method. This is one of many new methods added to the old date-time classes for converting to/from java.time objects.
Using such a conversion method makes your code more self-documenting. Also makes more clear your awareness that you are consciously moving between the modern & legacy classes.
String input = "2017-09-18T03:08:20.888+0200";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f ); // Parse input.
ZoneOffset offset = odt.getOffset( ); // Interrogate for the `ZoneOffset` object representing this moment’s offset-from-UTC (a number of hours/minutes/seconds).
TimeZone tz = TimeZone.getTimeZone( offset ); // Convert from modern java.time object (a `ZoneOffset`/`ZoneId`) to the legacy class `TimeZone`.
Dump to console.
System.out.println( "odt.toString(): " + odt );
System.out.println( "offset.toString(): " + offset );
System.out.println( "tz.toString(): " + tz );
odt.toString(): 2017-09-18T03:08:20.888+02:00
offset.toString(): +02:00
tz.toString(): sun.util.calendar.ZoneInfo[id="GMT+02:00",offset=7200000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.