SimpleDateFormat 格式错误的值

发布于 2024-10-09 15:56:02 字数 515 浏览 4 评论 0原文

以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娇妻 2024-10-16 15:56:02

你正在混合毫秒和秒。
1293253200 确实是 2010 年 1 月 16 日。您必须乘以 1000 才能得到您想要的日期:

Date date = new Date(1293253200L*1000L);
Sat Dec 25 06:00:00 CET 2010

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 date = new Date(1293253200L*1000L);
Sat Dec 25 06:00:00 CET 2010
清旖 2024-10-16 15:56:02

请检查 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.

清旖 2024-10-16 15:56:02

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.

空城缀染半城烟沙 2024-10-16 15:56:02

正如 mhaller 所指出的,在这种情况下,您确实弄错了毫秒和秒。

< 的重载构造函数code>Date 其参数为 long。以下来自 java-doc 页面的片段。

参数:

日期 -
自 1970 年 1 月 1 日 00:00:00 GMT 起的毫秒数不超过
8099 年的毫秒表示。负数
表示1970年1月1日00:00:00之前的毫秒数
格林威治标准时间。

As pointed by mhaller, you have indeed mistaken the milli-seconds and seconds in this case.

The overloaded constuctor of Date takes its parameter as long. The following snippet from the java-doc page.

Parameters:

date -
milliseconds since January 1, 1970, 00:00:00 GMT not to exceed the
milliseconds representation for the year 8099. A negative number
indicates the number of milliseconds before January 1, 1970, 00:00:00
GMT.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文