Java Programming - Java timestamp, time conversion

Hi,

I need to convert a java timestamp which is in EST/EDT (Eastern standard/daylight time) to a timestamp in MST (mountain standard time) that reflects the time in MST.

Here is the code i have written. I wanted to know if there was a better way of doing this:

private Timestamp convertToMST(Timestamp stamp){

TimeZone tzMST = TimeZone.getTimeZone("MST");

TimeZone tzLocal = TimeZone.getDefault();

int dayLightSavingsOffset = 0;

if(tzLocal.useDaylightTime()){

// check that the timestamp stamp is in DST.

if(tzLocal.inDaylightTime(new Date(stamp.getTime()))){

// the timestamps timezone is following daylight savings time

// so subtract the amount to time of the daylight savings from the timestamp

dayLightSavingsOffset = tzLocal.getDSTSavings();

}

}

int mstOffSet = tzMST.getRawOffset();

int localOffSet = tzLocal.getRawOffset();

if(mstOffSet<0) mstOffSet=Math.abs(mstOffSet);

if(localOffSet<0) localOffSet=Math.abs(localOffSet);

// subtract the 2

int diff = mstOffSet - localOffSet;

diff = Math.abs(diff);

long current = stamp.getTime() - dayLightSavingsOffset;

if(mstOffSet>localOffSet){

current = current - diff; // subtract diff from current

}else if(mstOffSet<localOffSet){

current = current + diff; // add diff to current

} // if not these --simply return current

return new Timestamp(current);

}

Thank you

[1513 byte] By [roysilveiraa] at [2007-11-26 23:26:22]
# 1

Yes, there is. The Calendar class implements all that DST business that you are doing there. So let it do that for you:

Calendar cal = Calendar.getInstance();

cal.setTime(stamp);

// assuming your default timezone is America/New_York

Calendar newcal = Calendar.getInstance();

newcal.setTimeZone(TimeZone.getTimeZone("America/Phoenix");

// or America/Denver, you choose...

newcal.set(Calendar.YEAR, cal.get(Calendar.YEAR));

newcal.set(Calendar.MONTH, cal.get(Calendar.MONTH));

newcal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH));

newcal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));

newcal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));

newcal.set(Calendar.SECOND, cal.get(Calendar.SECOND));

return newcal;

Note that those three-character abbreviations for timezones have been deprecated for about six years now.

DrClapa at 2007-7-10 14:34:20 > top of Java-index,Java Essentials,Java Programming...
# 2
Note that those three-character abbreviations for timezones have been deprecated for about six years now.Further, TimeZone.getTimeZone("EST") thinks that it's NOT in DST, so take it as more than just a warning.
KelVarnsona at 2007-7-10 14:34:20 > top of Java-index,Java Essentials,Java Programming...