GetMilliseconds () from Java Date

I need a function like long getMillis (Date aDate);

which returns the milliseconds of the second second. I can not use Yoda, SimpleDateFormat or other libraries because it is gwt code.

My current solution is making date.getTime() % 1000

Is there a better way?

+8
java date milliseconds
source share
3 answers

As Peter Lowry pointed out, in general you need something like

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

since % works on a “weird” path in Java. I call it strange, because I always need the result to fall within the given range (here: 0..999), and not get negative results. Unfortunately, it works this way on most processors and in most languages, so we have to live with it.

+6
source share

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

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

TL; DR

 aDate.toInstant() .toEpochMilli() 

java.time

The modern approach uses java.time classes. They crowd out difficult old heritage classes such as java.util.Date .

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

1970-01-01T00:00:00Z millisecond counter from the 1970-01-01T00:00:00Z .

 long millis = instant.toEpochMilli() ; 

Conversion

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

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

Source: https://habr.com/ru/post/651286/


All Articles