Java将日期转换为纪元值会产生错误的输出 [英] Java Converting date to epoch value produces false output
问题描述
我正在尝试将以下日期时间字符串对象转换为unix纪元时间戳记值。但是,当我运行程序,我注意到它产生的时代值1404461110000当我检查我的ubuntu unix机器是Wed Aug 7 18:06:40但是在现实中我正在通过七月04 2014-07-04 04: 05:10我在ubuntu机器上有美洲/多伦多的时区,但我认为这不重要吗?
I am trying to convert the below date time string object into a unix epoch timestamp value. However, when i run the program i notice that it generates an epoch value of 1404461110000 which when i check on my ubuntu unix machine is Wed Aug 7 18:06:40 However in reality i am passing July 04 2014-07-04 04:05:10. I have a time zone of America/Toronto on my ubuntu machine but I don't think it should matter here ?
Java代码:
long epoch = 0;
String str = "2014-07-04 04:05:10"; // UTC
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date datenew = df.parse(str);
epoch = datenew.getTime();
System.out.println(epoch); // prints 1404461110000
Ubuntu Linux 14.04
Ubuntu Linux 14.04
date -d@1404461110000
显示= Wed Aug 7 18 :06:40 EDT 46475
displays= Wed Aug 7 18:06:40 EDT 46475
推荐答案
问题是你没有处理 getTime()时,/en.wikipedia.org/wiki/Unix_timerel =nofollow> unix timestamp 。从时代起,Unix时间戳以秒表示,而从 milliseconds 。 org / wiki / Epoch_%28reference_date%29rel =nofollow> epoch (1970年1月1日),因此有区别。
The issue is that you're not dealing with a unix timestamp when calling getTime()
in Java. Unix timestamps are expressed in seconds since the epoch, while the values you're getting from Java are milliseconds since the epoch (Jan 01 1970), hence the difference.
是:
epoch = datenew.getTime() / 1000;
这应该让你至少有一万年的距离。如果您仍然看到差异,那么它是与时区相关的,可以通过在 DateFormat
实例中指定时区来实现。
This should get you at least a couple of 10000 years closer. If you still see a difference after that, it's timezone-related, and can be accommodated for by specifying the timezone on your DateFormat
instance.
这篇关于Java将日期转换为纪元值会产生错误的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!