SimpleDateFormat 格式错误的值
以下代码:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
System.out.println(sdf.format(new Date(1293253200))); // 12/25/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293339600))); // 12/26/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293426000))); // 12/27/2010 05:00 GMT
打印:
01/16
01/16
01/16
通过 SimpleDateFormat.getDateInstance(); 使用默认的
DateFormat
将这些日期打印为 16-Jan-1970
。到底是怎么回事?
The following code:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
System.out.println(sdf.format(new Date(1293253200))); // 12/25/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293339600))); // 12/26/2010 05:00 GMT
System.out.println(sdf.format(new Date(1293426000))); // 12/27/2010 05:00 GMT
prints:
01/16
01/16
01/16
Using a default DateFormat
via SimpleDateFormat.getDateInstance();
prints these dates as 16-Jan-1970
. What is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你正在混合毫秒和秒。
1293253200 确实是 2010 年 1 月 16 日。您必须乘以 1000 才能得到您想要的日期:
You are mixing milliseconds and seconds.
1293253200 is indeed 16. January 2010. You have to multiply with 1000 to get the dates you wanted:
请检查
Date(long)
构造函数的文档:它的值以毫秒为单位,而不是秒。new Date(1293253200000l)
应该就可以了。附言。许多 IDE 提供内联文档,因此您甚至不必打开浏览器。
Please check documentation of
Date(long)
constructor: it takes values in milliseconds, not seconds.new Date(1293253200000l)
should do just fine.PS. Many IDE's provide inline documentation, so you don't even have to open the browser.
Date
构造函数期望自纪元以来的毫秒数,但您传递的数字是自纪元以来的秒数。将其乘以 1,000,即可得到正确的日期。The
Date
constructor expects a number of milliseconds since the epoch, but the number you're passing is in seconds since the epoch. Multiply it by 1,000 and you'll get the right date.正如 mhaller 所指出的,在这种情况下,您确实弄错了毫秒和秒。
< 的重载构造函数code>Date 其参数为
long
。以下来自 java-doc 页面的片段。As pointed by mhaller, you have indeed mistaken the milli-seconds and seconds in this case.
The overloaded constuctor of
Date
takes its parameter aslong
. The following snippet from the java-doc page.