getMilliseconds() out of Java Date

Uberto picture Uberto · Jan 20, 2011 · Viewed 17.6k times · Source

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?

Answer

maaartinus picture maaartinus · Jan 20, 2011

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.