1

出于某种原因,我总是很难正确显示时间戳,但无论如何这是我的问题。

我正在从中提取事件,Calendar Provider API并且某些事件(例如US Holidays日历事件)采用 UTC,因此时间戳不是设备上应有的时间戳(当然,除非设备位于该时区)。

我有一个时间戳,1374105600000它是07/18/2013 00:00:00 UTC7 月 18 日午夜 UTC。我想要的是 7 月 18 日午夜本地设备时间的时间戳。

这就是我所做的

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTimeInMillis(time);

long offset = tz.getRawOffset(); //gives me -18000000 5hr difference since I am in EST which I think is actually wrong because it should be a 4hr difference now with DST

因此,如果我将其添加到 UTC 时间戳

long local = time+offset;

它给了我不正确的时间july 17th at 3:00PM

如果我减去时间

long local = time-offset;

我仍然得到错误的时间,它给了我,july 18th at 1:00AM但我认为我什至不应该减去,因为这对+时区差异的人不起作用。

我在做什么错,为什么我不能获得正确的偏移量来获得正确的时间?

我也将其用作参考链接

4

2 回答 2

2

由于Java does notATTACHTimezone使用对象来附加信息Date,因此进行转换有点奇怪。请查看下面的清单,我正在尝试将时间从“UTC”(格林威治标准时间)转换为“EST”(可以是纽约的时区)

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class TimeZoneTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Calendar gmtTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        Calendar estTime = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
        
        System.out.println(getInputDate() + " (Actually GMT)");
        estTime.setTime(getInputDate());
        
        gmtTime.clear();
        gmtTime.set(estTime.get(Calendar.YEAR), estTime.get(Calendar.MONTH), 
                estTime.get(Calendar.DAY_OF_MONTH), estTime.get(Calendar.HOUR_OF_DAY), estTime.get(Calendar.MINUTE));
        gmtTime.set(Calendar.SECOND, estTime.get(Calendar.SECOND));
        Date estDate = gmtTime.getTime();
        System.out.println(estDate + "(Actually EST)");
    }
    
    private static Date getInputDate() {
        Calendar instance = Calendar.getInstance();
        instance.clear();
        instance.set(2014, 3, 2, 9, 0, 0);
        Date input = instance.getTime();
        return input;
    }

}

输出是

Wed Apr 02 09:00:00 IST 2014 (Actually GMT)
Wed Apr 02 05:00:00 IST 2014(Actually EST)

这实际上是正确的

编辑:重要的是使用“America/New_York”而不是“EST”来考虑夏令时

于 2013-04-02T01:12:31.580 回答
0

嗯..下面的代码颠倒了你的场景,但也许你可以利用它?

private  Date cvtToGmt( Date date )
{
   TimeZone tz = TimeZone.getDefault();
   Date ret = new Date( date.getTime() - tz.getRawOffset() );

   // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
   if ( tz.inDaylightTime( ret ))
   {
      Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

      // check to make sure we have not crossed back into standard time
      // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
      if ( tz.inDaylightTime( dstDate ))
      {
         ret = dstDate;
      }
   }

   return ret;
}
于 2013-04-02T00:48:31.347 回答