문제

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?

도움이 되었습니까?

해결책

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() ;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top