Java 日期中的 getMilliseconds()
我需要一个像这样的函数 长 getMillis(Date aDate);
返回日期秒的毫秒数。 我无法使用 Yoda、SimpleDateFormat 或其他库,因为它是 gwt 代码。
我当前的解决方案是执行 date.getTime() % 1000
有更好的方法吗?
I need a function like
long getMillis(Date aDate);
that returns the milliseconds of the Date second.
I cannot use Yoda, SimpleDateFormat or other libraries because it's gwt code.
My current solution is doing date.getTime() % 1000
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Peter Lawrey 所指出的,一般来说,您需要类似的东西,
因为
%
在 Java 中以一种“奇怪”的方式工作。我称其为奇怪,因为我总是需要结果落入给定范围(此处:0..999),而不是有时得到负结果。不幸的是,它在大多数 CPU 和大多数语言中都是这样工作的,所以我们必须忍受它。As pointed by Peter Lawrey, in general you need something like
since
%
works in a "strange" way in Java. I call it strange, as I always need the result to fall into a given range (here: 0..999), rather than sometimes getting negative results. Unfortunately, it works this way in most CPUs and most languages, so we have to live with it.尝试上面并得到意想不到的行为,直到我使用 1000 作为长的 mod。
Tried above and got unexpected behavior until I used the mod with 1000 as a long.
tl;dr
java.time
现代方法使用 java.time 类。它们取代了麻烦的旧遗留类,例如 java.util.Date。
提取自
1970-01-01T00:00:00Z
纪元以来的毫秒数。转换
如果您传递了一个 java.util.Date 对象,请转换为 java.time。调用添加到旧类中的新方法。
tl;dr
java.time
The modern approach uses java.time classes. These supplant the troublesome old legacy classes such as
java.util.Date
.Extract your count of milliseconds since epoch of
1970-01-01T00:00:00Z
.Converting
If you are passed a
java.util.Date
object, convert to java.time. Call new methods added to the old classes.