Java 日期中的 getMilliseconds()

发布于 2024-10-12 15:30:38 字数 180 浏览 6 评论 0原文

我需要一个像这样的函数 长 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 技术交流群。

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

发布评论

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

评论(3

各自安好 2024-10-19 15:30:38

正如 Peter Lawrey 所指出的,一般来说,您需要类似的东西,

int n = (int) (date.getTime() % 1000);
return n<0 ? n+1000 : n;

因为 % 在 Java 中以一种“奇怪”的方式工作。我称其为奇怪,因为我总是需要结果落入给定范围(此处:0..999),而不是有时得到负结果。不幸的是,它在大多数 CPU 和大多数语言中都是这样工作的,所以我们必须忍受它。

As pointed by Peter Lawrey, in general you need something like

int n = (int) (date.getTime() % 1000);
return n<0 ? n+1000 : n;

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.

平安喜乐 2024-10-19 15:30:38

尝试上面并得到意想不到的行为,直到我使用 1000 作为长的 mod。

int n = (int) (date.getTime() % 1000l);
return n<0 ? n+1000 : n;

Tried above and got unexpected behavior until I used the mod with 1000 as a long.

int n = (int) (date.getTime() % 1000l);
return n<0 ? n+1000 : n;
孤君无依 2024-10-19 15:30:38

tl;dr

aDate.toInstant()
     .toEpochMilli()

java.time

现代方法使用 java.time 类。它们取代了麻烦的旧遗留类,例如 java.util.Date。

Instant instant = Instant.now();  // Capture current moment in UTC.

提取自 1970-01-01T00:00:00Z 纪元以来的毫秒数。

long millis = instant.toEpochMilli() ;

转换

如果您传递了一个 java.util.Date 对象,请转换为 java.time。调用添加到旧类中的新方法。

Instant instant = myJavaUtilDate.toInstant() ;
long millis = instant.toEpochMilli() ;

tl;dr

aDate.toInstant()
     .toEpochMilli()

java.time

The modern approach uses java.time classes. These supplant the troublesome old legacy classes such as java.util.Date.

Instant instant = Instant.now();  // Capture current moment in UTC.

Extract your count of milliseconds since epoch of 1970-01-01T00:00:00Z.

long millis = instant.toEpochMilli() ;

Converting

If you are passed a java.util.Date object, convert to java.time. Call new methods added to the old classes.

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