Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the "America/Los Angeles" time zone to "PST" or "PDT" in Java ME

My server sends me time zones of the format "America/Los Angeles". On the client, I have a time that I need to display in that time zone. The answer will be "PST" or "PDT", depending on daylight savings at the given time. How do I do that conversion?

I'm on Java ME (Blackberry 4.7, to be accurate), so I can't use Joda Time.

I will need to make this calculation rapidly for a lot of dates (but only one time zone), so I can't just have the server send me an offset, because the offset might change depending on the date.

Edit: Let me restate the problem, because there seems to be some confusion. I am given a zoneinfo name and a date. I want to know the offset from GMT in that timezone at that date. The answer will vary depending on daylight savings time.

As an added bonus, I'd like to get the TLA to show to the user (i.e., "PST" or "PDT"), but that's secondary.

Solution: I'll summarize the solution here, because it isn't terribly clear from the answers below. This essentially does what I need, in J2ME:

TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles");
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(zone);

calendar.setTime(new Date(2011, 1, 1, 12, 0, 0));      
System.out.println(zone.getOffset(1, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_WEEK), calendar.get(Calendar.MILLISECOND)));
calendar.setTime(new Date(2011, 6, 1, 12, 0, 0));
System.out.println(zone.getOffset(1, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.DAY_OF_WEEK), calendar.get(Calendar.MILLISECOND)));
like image 420
Dirk Groeneveld Avatar asked Feb 01 '11 23:02

Dirk Groeneveld


1 Answers

May be this is what you are wanting. This works on my machine using standard java.

        Calendar calendar = Calendar.getInstance();       
        TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
        calendar.setTimeZone(tz);
         System.out.println("Offset from UTC="+tz.getOffset(calendar.getTimeInMillis())/(60*60*1000)); //prints -8
        System.out.println(tz.getDisplayName(Boolean.TRUE, 0)); //prints PDT
        System.out.println(tz.getDisplayName(Boolean.TRUE, 1)); //prints Pacific Daylight Time
        System.out.println(tz.getDisplayName(Boolean.FALSE, 0));//prints PST
        System.out.println(tz.getDisplayName(Boolean.FALSE, 1));//prints Pacific Standard Time  

Update: OP said the above does not work for j2ME. After googling I found here that getOffset() is actually getRawOffset() in j2me. However, it does not look like it supposrts displayName. Your only option I think is to go through the ids using getAvailableIds().

like image 105
CoolBeans Avatar answered Sep 28 '22 15:09

CoolBeans