Frage

Ich brauche eine Funktion wie lange getMillis (Datum aDate);

, dass kehrt die Millisekunden des Datums Sekunde. Ich kann nicht verwenden Yoda, Simple oder andere Bibliotheken, weil es GWT-Code ist.

Meine aktuelle Lösung tut date.getTime() % 1000

Gibt es einen besseren Weg?

War es hilfreich?

Lösung

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.

Andere Tipps

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() ;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top