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

前端 未结 5 813
余生分开走
余生分开走 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:43

    Simple Method for Obtaining Timezone Name and Offset in Hours

    public static String getCurrentTimeZoneOffset() {
        DateTimeZone tz = DateTimeZone.getDefault();
        Long instant = DateTime.now().getMillis();
    
        String name = tz.getName(instant);
    
        long offsetInMilliseconds = tz.getOffset(instant);
        long hours = TimeUnit.MILLISECONDS.toHours( offsetInMilliseconds );
        String offset = Long.toString( hours );
    
        return name + " (" + offset + " Hours)";
        // Example: "Mountain Standard Time (-7 Hours)"
    }
    

    Couple caveats:

    • This gets the default DateTimeZone from JodaTime. You can modify it to accept a specific DateTimeZone that is passed into the method.
    • This returns it in a format like "Mountain Standard Time (-7 Hours)" but you can format it as you see fit quite easily.

    Hope that helps.

    JP

提交回复
热议问题