我从两个不同的日期获取毫秒,尝试将毫秒转换为时间戳。我编写了以下代码。
Date d1 = new Date();
for(int i=0;i<1000000;i++){
System.out.println(i);
}
Date d2 = new Date();
System.out.println(d1);
System.out.println(d2);
long seconds = d2.getTime()-d1.getTime();
Date d3 = new Date(seconds);
DateFormat df = new SimpleDateFormat("HH:mm:ss");
System.out.println(seconds);
System.out.println("Time is : "+df.format(d3));
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(seconds);
System.out.println(df.format(cal.getTime()));
for循环需要2或3秒,结果可能是00:03:80,但我的结果总是得到
Time is : 05:30:04
05:30:04
但实际差异是 2 或 3 秒,这是正确的方法还是有其他方法。
最佳答案
设置时区:
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(seconds);
System.out.println("Time is : "+df.format(d3));
Date
类以毫秒为单位测量自 1970 年 1 月 1 日 00:00:00 UTC 以来的时间。您的本地时间似乎比 UTC 早 5 小时 - 或者是 1970 年 1 月 1 日 - 使得 UTC“零”日期出现在您所在时区的凌晨 5 点。
关于java - 如何获取时间(hh :mm:ss) from two different dates in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17419956/