getMilliseconds() 超出 Java 日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4745438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getMilliseconds() out of Java Date
提问by Uberto
I need a function like long getMillis(Date aDate);
我需要一个像 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.
返回 Date 秒的毫秒数。我不能使用 Yoda、SimpleDateFormat 或其他库,因为它是 gwt 代码。
My current solution is doing date.getTime() % 1000
我目前的解决方案正在做 date.getTime() % 1000
Is there a better way?
有没有更好的办法?
采纳答案by maaartinus
As pointed by Peter Lawrey, in general you need something like
正如 Peter Lawrey 所指出的,一般来说你需要类似的东西
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 alwaysneed 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.
因为%
在 Java 中以“奇怪”的方式工作。我称之为奇怪,因为我总是需要结果落在给定的范围内(此处:0..999),而不是有时得到负面结果。不幸的是,它在大多数 CPU 和大多数语言中都是这样工作的,所以我们必须忍受它。
回答by Joseph Valerio
Tried above and got unexpected behavior until I used the mod with 1000 as a long.
在上面尝试过并得到了意想不到的行为,直到我使用 1000 作为长期的 mod。
int n = (int) (date.getTime() % 1000l);
return n<0 ? n+1000 : n;
回答by Basil Bourque
tl;dr
tl;博士
aDate.toInstant()
.toEpochMilli()
java.time
时间
The modern approach uses java.time classes. These supplant the troublesome old legacy classes such as java.util.Date
.
现代方法使用 java.time 类。这些取代了麻烦的旧遗留类,如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
.
提取自纪元以来的毫秒数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.
如果传递了一个java.util.Date
对象,则转换为 java.time。调用添加到旧类的新方法。
Instant instant = myJavaUtilDate.toInstant() ;
long millis = instant.toEpochMilli() ;