Wednesday, July 25, 2007

Getting Java Date in another Timezone

Getting the date in another timezone is not quite as evident. But I did whip up a method to return the Date object if you provide your local Date and the timeZone id of where you want to find out what time it is there.

import java.util.*;

public class Timezone {

public static Date getDateInTimeZone(Date currentDate, String timeZoneId)
{
TimeZone tz = TimeZone.getTimeZone(timeZoneId);
Calendar mbCal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneId));
mbCal.setTimeInMillis(currentDate.getTime());

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, mbCal.get(Calendar.YEAR));
cal.set(Calendar.MONTH, mbCal.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, mbCal.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, mbCal.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, mbCal.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, mbCal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, mbCal.get(Calendar.MILLISECOND));

return cal.getTime();
}

public static void main(String[] args)
{
Date now = new Date();

System.out.println("Current Time="+now);
Calendar cal = Calendar.getInstance();
System.out.println("Current Timezone="+cal.getTimeZone().getDisplayName());

//Canada/Central
String timeZoneId = "Canada/Central";
System.out.println("Getting Time in the timezone="+timeZoneId);
System.out.println("Current Time there="+getDateInTimeZone(now,timeZoneId));
}

}

205 comments:

«Oldest   ‹Older   201 – 205 of 205
Anonymous said...

Great article, just what I wanted to find.

My webpage :: http://bobshots.net/groups/staying-power-for-guys-in-the-long-run-conclusion-earlier-comprar-viagra/

Anonymous said...

Very great post. I simply stumbled upon your
weblog and wished to mention that I have really enjoyed surfing
around your weblog posts. In any case I'll be subscribing to your rss feed and I hope you write once more soon!

Here is my weblog ... http://sloanforum.com/

Anonymous said...

Your οwn гeport has estаbliѕhed neceѕsary to me
personally. It’s еxtremely helpful and you're clearly quite educated in this area. You have popped my personal eye to varying opinion of this specific matter using intriguing and reliable articles.

Here is my page ambien

Anonymous said...

e cigarette forum, electronic cigarette, smokeless cigarettes, smokeless cigarettes, e cigarette, e cigarette

macwintech said...

Your post is awesome we like your post and it is very informative in which we now come to understand how we can set time.
Computer Repair Hong Kong
Laptop Apple Repair HK
iPhone Repair

«Oldest ‹Older   201 – 205 of 205   Newer› Newest»