I have written this method for converting a date time zone. How do i reduce the execution time of this method further.
public static Timestamp convertTimeZone(final Timestamp fromDate, final TimeZone fromTZ, final TimeZone toTZ ){
Long timeInDate = fromDate.getTime() ;
int fromOffset = fromTZ.getOffset(timeInDate);
int toOffset = toTZ.getOffset(timeInDate);
Timestamp dateStamp = new Timestamp(fromDate.getTime());
if (fromOffset >= 0){
int diff = 0;
if (toOffset > 0){
diff = (fromOffset - toOffset);
} else {
diff = (fromOffset + Math.abs(toOffset));
}
long date = fromDate.getTime() - diff;
dateStamp.setTime(date);
} else {
int diff = 0;
if (toOffset > 0){
diff = (Math.abs( fromOffset) + toOffset);
} else {
diff = (Math.abs( fromOffset) - Math.abs(toOffset));
}
long date = fromDate.getTime() + diff;
dateStamp.setTime(date);
}
return dateStamp;
}
With joda-time it may look like this:
Note that
Timestamp
has no notion of Timezone so it is not suitable for representing it.Your solution will have a good running time, since it's O(1). It's harder to read though.
You could store your date in a Calendar object to begin with. Showing it in different time zone formats will be a matter of configuration that you apply to a SimpleDateFormat.
Technically a Date is the same in all time zones (it's internal value is the same). Applying the concept of timezones allows date formatters to adjust offsets for display. In other words, a Date that represents 17:00 in London time is equal to a Date that represents 12:00 in New York. Displaying it in the GMT vs. the EST time zones can be a function of date formatters.
It's not quite an answer, but I recommend always store timestamp in database as UTC time instead of local time. And display it for different timezones only on presentation layer setting
DateFormat.setTimeZone()