如何将纪元的年月日转换为正确的 UTC 毫秒?
我正在尝试使用以下代码将日期转换为毫秒:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
gc.clear();
gc.set(1900, 1, 1);
long left = gc.getTimeInMillis();
我得到 left=-2206310400000
,但是当我检查 这里,我应该得到-2208988800000。
我做错了什么?
I am trying to convert a date into milliseconds with the following code:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
gc.clear();
gc.set(1900, 1, 1);
long left = gc.getTimeInMillis();
I get left=-2206310400000
, but when I check here, I should get -2208988800000.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用 1 表示月份数字,这意味着二月。
您的意思是
来自
是的,Java 日期/时间 API 已损坏。如果您在日期/时间方面要做大量工作,我建议您使用 Joda Time反而。
You're using 1 for the month number, which means February.
You mean
From the docs:
Yes, the Java date/time API is broken. If you're doing any significant amount of work in dates/times, I'd suggest you use Joda Time instead.
java.time
java.util
Date-Time API 及其格式化 APISimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 现代日期时间 API*。另外,下面引用的是Joda-Time主页的通知< /a>:
使用现代日期时间 API
java.time
的解决方案:输出:
在线演示
从跟踪:日期时间。
* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport 将大部分 java.time 功能向后移植到 Java 6 和 Java 6 7. 如果您正在处理 Android 项目,并且您的 Android API 级别仍然不符合 Java-8,请检查 通过脱糖提供 Java 8+ API 和 如何在 Android 项目中使用 ThreeTenABP。
java.time
The
java.util
Date-Time API and their formatting API,SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.Also, quoted below is a notice from the home page of Joda-Time:
Solution using
java.time
, the modern Date-Time API:Output:
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.