NimChimpsky
NimChimpsky

Reputation: 47310

Java remove millisecond precision from long value

so from this :

1459245759880

to this

1459245759000

Upvotes: 2

Views: 636

Answers (3)

assylias
assylias

Reputation: 328923

Usual integer rounding?

long millis = 1459245759880L;
long rounded = millis / 1000 * 1000;

Using Java time (convenient if you need to do date/time operations on the result - in that case you can work with the instant):

Instant i = Instant.ofEpochMilli(millis).truncatedTo(ChronoUnit.SECONDS);
long rounded = i.toEpochMilli();

More convoluted (and probably not very clear):

long rounded = 1000 * TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
//OR
long rounded = TimeUnit.MILLISECONDS.convert(TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS), TimeUnit.SECONDS);

Upvotes: 4

Panther
Panther

Reputation: 3339

 long x = 1459245759880;
 long y = x - (x % 1000);

Use simply the modulo operator to get reminder and then subtract it from the actual value.

Upvotes: 3

Deb
Deb

Reputation: 2972

Why not this

long value = 1459245759880L;
System.out.println(1000 * (value / 1000));

Upvotes: 1

Related Questions