Joda-Time
Doing date-time work much easier and simpler with the Joda-Time library than with the notoriously troublesome bundled java.util.Date & .Calendar classes.
Time Zone
Using proper time zone names, rather than a specific offset, is generally a wiser approach.
Example Code
Here is some example code using Joda-Time 2.3.
Notice:
- Joda-Time has built-in parsers for strings in ISO 8601 format. No need to instantiate parsing or formatting objects.
- Joda-Time is both parsing the UTC string and adjusting it to another time zone all in one call to the
DateTime
constructor.
- When converting to a UTC-based dateTime in the last line, we still have the same moment in the timeline of the Universe (same count of milliseconds since Unix epoch).
Source…
String input = "2014-04-02T07:59:02.111Z";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Dubai" );
DateTime dateTimeDubai = new DateTime( input, timeZone ); (a) Parse, (b) Adjust time zone.
DateTime dateTimeUtc = dateTimeDubai.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeDubai: " + dateTimeDubai );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 2014-04-02T07:59:02.111Z
dateTimeDubai: 2014-04-02T11:59:02.111+04:00
dateTimeUtc: 2014-04-02T07:59:02.111Z