Using Joda-Time to get UTC offset for a given date and timezone

前端 未结 5 792
余生分开走
余生分开走 2021-01-01 19:03

I have dates in the format 20Jan2013, 08Aug2012 etc, with their own specific timezones. So for example, 20Jan2013 might have a timezone ID of Australia/Melbourne, and 08Aug2

5条回答
  •  时光取名叫无心
    2021-01-01 19:47

    If you just need the timezone offset, use DateTimeZone.forID() to get the time zone and then tz.getOffset(instant) to get the offset to UTC in milliseconds.

    It may look odd that you need an instant to calculate the offset to UTC but this is necessary to take Daylight Savings into account as well as changes in the timezone. Yes, countries change their timezones once in a while:

    Why does timezone data change?

    Timezone settings are adopted locally, and there is no world timezone authority.

    EDIT This gives you the correct result:

        DateTimeFormatter dtf1 = DateTimeFormat.forPattern("ddMMMYYYY");
    
        DateTimeZone zone = DateTimeZone.forID("Australia/Melbourne");  
    
        DateTime thisDate = dtf1.parseDateTime("30Jul2013").withZone(zone);                                            
        assertEquals( 10 * CommonConstants.MILLISECONDS_PER_HOUR,
            zone.getOffset( thisDate ) );
    

    thisDate.get

提交回复
热议问题