开发者

getMilliseconds() out of Java Date

开发者 https://www.devze.com 2023-02-05 22:30 出处:网络
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.

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开发者_如何学C current solution is doing date.getTime() % 1000

Is there a better way?


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.


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;


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() ;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号