Converting timezone for date faster using java

2019-09-04 14:46发布

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;
}

3条回答
【Aperson】
2楼-- · 2019-09-04 15:25

With joda-time it may look like this:

DateTime dt = new DateTime(DateTimeZone.forID("GMT"));
System.out.println(dt); // 5 am
dt = dt.withZone(DateTimeZone.forID("EET"));
System.out.println(dt); // 8 am

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.

查看更多
不美不萌又怎样
3楼-- · 2019-09-04 15:30

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.

查看更多
姐就是有狂的资本
4楼-- · 2019-09-04 15:35

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()

查看更多
登录 后发表回答