Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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() ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top