我不知道我在这里做错了什么。我有一个时间戳(长),并试图将其更改为可读格式。
这是时间戳:
1404162530517
当我使用纪元转换器验证时间时,它说现在是下午 5:08(正确)
当我尝试使用我的代码解析它时,它显示 10:21PM(错误)
这是不起作用的代码:
long unixSeconds = Long.parseLong(tstamp);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
formattedDate = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"hh:mma ", Locale.ENGLISH);
timeDate = timeFormat.format(date);
System.out.println(tstamp);
System.out.println(timeDate);
我该如何解决这个问题?
最佳答案
好的,您所在的时区是 EDT。但是,Unix 时间戳是从 UTC 中的 Unix 纪元开始计算的。换句话说,您比 UTC 晚 5 小时,因此时间戳是从 UTC 1970 年午夜开始计算的 5 小时。
那么如何解决这个问题呢?在您的第一个 SimpleDateFormat
中,输入输入时区为 UTC。这应该将 UTC 转换为您的时间 (EDT):
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
formattedDate = dateFormat.format(date);
关于java - 将时间戳转换为时间会给出错误的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24501845/