Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip seconds and milliseconds from System.currentTimeMillis value

Tags:

java

time

Suppose I have a System.currentTimeMillis() value as a long number.

How do I modify it to match the instant when last minute started? I.e., zero out seconds and milliseconds.

I would prefer to not use magic constants. Using java.time is fine.

like image 816
alamar Avatar asked Oct 16 '25 18:10

alamar


1 Answers

I agree with the answers recommending java.time, but it can be done yet simpler as in those answers:

    long lastWholeMinute = Instant.now().truncatedTo(ChronoUnit.MINUTES).toEpochMilli();

This just gave 1517940060000. Of course, if it makes sense for you to keep the Instant object, by all means do that rather than converting to a naked primitive long.

If your long value was one you had stored rather than the time now, it’s quite similar:

    long someEpochMilliValue = 1_517_941_234_567L;
    long lastWholeMinute = Instant.ofEpochMilli(someEpochMilliValue)
            .truncatedTo(ChronoUnit.MINUTES)
            .toEpochMilli();
like image 53
Ole V.V. Avatar answered Oct 18 '25 10:10

Ole V.V.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!