2013-04-02 224 views
1

出于某种原因,我总是最难获得时间戳来正确显示,但无论如何,这是我的问题。将UTC时间戳转换为本地设备时间戳

我从Calendar Provider API拉事件和一些事件,如US Holidays日历事件是UTC,所以时间戳不是它应该在设备上(除非该设备是在该时区当然)。

我有这个1374105600000的时间戳,这是07/18/2013 00:00:00 UTC所以七月十八号在午夜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,但我不认为我应该减去,因为这将不会为+时区差异的人工作。

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

我也是用这个像作为参考太Link

回答

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

由于Java does not附加Timezone信息与Date对象,它有点不可思议做转换。请检查下面的清单,在那里我想的时间从“UTC”(GMT)转​​换为“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) 

这实际上是correct

编辑:它的重要的是使用“美国/纽约”,而不是“EST”考虑夏令