Kirk Backus
Kirk Backus

Reputation: 4866

Convert DateTimeZone to UTC Offset

Given a DateTimeZone, I can get the name and ID of the TimeZone like this:

DateTimeZone timeZone = new DateTimeZone("America/Chicago");

// Prints "America/Chicago"
System.out.println(timeZone.getID());

// Prints "CDT" (Since it is daylight savings time now)
System.out.println(timeZone.getNameKey(DateTimeUtils.currentTimeMillis()));

// Prints "Central Daylight Time"
System.out.println(timeZone.getName(DateTimeUtils.currentTimeMillis()));

All are great, but I really would like to get the timezone as a UTC offset. In this case the UTC offset would look like -05:00

How do I do this with Joda-Time?

Upvotes: 2

Views: 783

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44061

A pure Joda-solution looks like:

int offsetMillis =
    DateTimeZone.forID("America/Chicago").getOffset(DateTimeUtils.currentTimeMillis());
DateTimeZone zone = DateTimeZone.forOffsetMillis(offsetMillis);
String utcOffset = zone.toString();
System.out.println(utcOffset); // output: -05:00

Upvotes: 1

CMOS
CMOS

Reputation: 51

You can use the Date, SimpleDateFormat, and TimeZone to achieve what you want. Make a SimpleDateFormat by setting the TimeZone you want. And then use that to format a new Date();

Upvotes: 0

Related Questions