user1740005
user1740005

Reputation: 567

computing time based on TimeZones

my code computes the date and time correctly including the dayLightSaving time,when run on my local server from india. But when I run the same code from US server I am getting the time which is one hour ahead for the timeZoneId which is not abserving DST.

TimeZone tz = TimeZone.getTimeZone("America/Phoenix");
Date currTime = getDateByTZ(new Date(), tz);
System.out.println("currTime" + currTime);

public static Date getDateByTZ(Date d, TimeZone tz) throws Exception {

    if (tz == null) {
        tz = TimeZone.getDefault();
    }
    Integer tzOffSet = tz.getRawOffset();
    Integer tzDST = tz.getDSTSavings();
    Integer defOffSet = TimeZone.getDefault().getRawOffset();
    Integer defDST = TimeZone.getDefault().getDSTSavings();
    Calendar cal = Calendar.getInstance(tz);
    cal.setTime(d);
    if (tz.inDaylightTime(d)) {
        cal.add(Calendar.MILLISECOND, -defOffSet);
        cal.add(Calendar.MILLISECOND, -defDST);
        cal.add(Calendar.MILLISECOND, +tzOffSet);
        cal.add(Calendar.MILLISECOND, +tzDST);
    } else {
        cal.add(Calendar.MILLISECOND, -defOffSet);
        cal.add(Calendar.MILLISECOND, tzOffSet);
    }
    return cal.getTime();
}

Results from Localserver:

currTime:Mon Oct 22 01:52:21 IST 2012

Results from USserver:

currTime:Mon Oct 22 02:52:21 IST 2012

Upvotes: 3

Views: 182

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

This code doesn't make much sense. A Date object doesn't have to be transformed to be used in another time zone. It represents a universal instant.

What makes sense is to use the time zone when displaying (or formatting as a string) a Date object. In this case, you should simply set the time zone on the DateFormat instance, and the universal instant that constitutes a date will be formatted in order to make sense for the given time zone.

Date now = new Date(); // now, whatever the timezone is

DateFormat df = DateFormat.getDateTimeInstance();

df.setTimeZone(TimeZone.getDefault());
System.out.println("Now displayed in the default time zone : " + df.format(now));
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Now displayed in the New York time zone : " + df.format(now));

Upvotes: 3

Related Questions