我正在将时间戳转换为日期格式yyyy-MM-dd HH:mm:ss.SSS
,我将America/New_York
用作TimeZone
。每当我将时间戳转换为日期时,它比通常的日期和时间少一个小时。如何在java中解决这个问题?
以下是代码:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zone = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zone);
String finale = df.format(currentDate);
答案 0 :(得分:1)
尝试使用EST
替换America/New_York
,如
TimeZone zone = TimeZone.getTimeZone("EST");
<强>更新强>
这是我的测试代码:
String timestamp = "1431941838000";
long time = Long.valueOf(timestamp);
Date currentDate = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
TimeZone zoneNewYork = TimeZone.getTimeZone("America/New_York");
df.setTimeZone(zoneNewYork);
String finale = df.format(currentDate);
System.out.println(finale);
TimeZone zoneEst = TimeZone.getTimeZone("EST");
df.setTimeZone(zoneEst);
finale = df.format(currentDate);
System.out.println(finale);
我的结果如下:
2015-05-18 05:37:18.000
2015-05-18 04:37:18.000
答案 1 :(得分:0)
你在这一行中有一个额外的观点:
TimeZone zone = TimeZone.getTimeZone("America/New_York").;
// ^ here!!!
更新
如果您没有收到任何错误,则输出必须正确:
EST
为UTC
- 5小时。 America/New_York
冬季为EST
,夏季为E*D*T
,因此请检查String timestamp = "1431941838000";
是冬季还是夏季......
此代码可以正常使用:
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));
用它来检查你的时间:
long timestamp = "1431941838000";
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
calNewYork.setTime(new Date(timestamp));
System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":"
+ calNewYork.get(Calendar.MINUTE));