Uberto Uberto - 3 months ago 23
Java Question

getMilliseconds() out of Java Date

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

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.

Comments