Convert Date/Time for given Timezone - java

前端 未结 16 2289
孤城傲影
孤城傲影 2020-11-22 12:36

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone,

16条回答
  •  长发绾君心
    2020-11-22 12:42

    Joda-Time

    The java.util.Date/Calendar classes are a mess and should be avoided.

    Update: The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.

    Here's your answer using the Joda-Time 2.3 library. Very easy.

    As noted in the example code, I suggest you use named time zones wherever possible so that your programming can handle Daylight Saving Time (DST) and other anomalies.

    If you had placed a T in the middle of your string instead of a space, you could skip the first two lines of code, dealing with a formatter to parse the string. The DateTime constructor can take a string in ISO 8601 format.

    // © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
    // import org.joda.time.*;
    // import org.joda.time.format.*;
    
    // Parse string as a date-time in UTC (no time zone offset).
    DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
    DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2011-10-06 03:35:05" );
    
    // Adjust for 13 hour offset from UTC/GMT.
    DateTimeZone offsetThirteen = DateTimeZone.forOffsetHours( 13 );
    DateTime thirteenDateTime = dateTimeInUTC.toDateTime( offsetThirteen );
    
    // Hard-coded offsets should be avoided. Better to use a desired time zone for handling Daylight Saving Time (DST) and other anomalies.
    // Time Zone list… http://joda-time.sourceforge.net/timezones.html
    DateTimeZone timeZoneTongatapu = DateTimeZone.forID( "Pacific/Tongatapu" );
    DateTime tongatapuDateTime = dateTimeInUTC.toDateTime( timeZoneTongatapu );
    

    Dump those values…

    System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
    System.out.println( "thirteenDateTime: " + thirteenDateTime );
    System.out.println( "tongatapuDateTime: " + tongatapuDateTime );
    

    When run…

    dateTimeInUTC: 2011-10-06T03:35:05.000Z
    thirteenDateTime: 2011-10-06T16:35:05.000+13:00
    tongatapuDateTime: 2011-10-06T16:35:05.000+13:00
    

提交回复
热议问题