Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round off timestamp in milliseconds to nearest seconds?

How to round off the current timestamp in milliseconds to seconds?

If this is the current timestamp in milliseconds I have -

1384393612958

The if I am rounding off to nearest second then will it be like this?

Time in MS rounded off to nearest Second = 1384393612000

I might need to do this both in Java and C++.

like image 812
AKIWEB Avatar asked Dec 04 '13 20:12

AKIWEB


Video Answer


3 Answers

If you are using Python:

old_number = 1384393612958
new_number = 1000 * (old_number / 1000)

print new_number

Basically you want to use an integer number, divide by one thousand (to shave off the milli-seconds), and then multiple by thousand to get the ms value rounded to seconds.

like image 182
Suman Avatar answered Oct 16 '22 22:10

Suman


In Java you can use Calendar to something like this:

Calendar cal = Calendar.getInstance().setTimeInMillis(millisec);
int seconds = cal.get(Calendar.SECONDS);

Alternatively (and can work for C++ too) you can do:

int sec = ((millisec + 500) / 1000);

adding 500 ms allows you to round the number properly.

like image 4
Luca S. Avatar answered Oct 16 '22 21:10

Luca S.


tl;dr

Instant.ofEpochMilli( 1_384_393_612_958L ) 
       .truncatedTo( ChronoUnit.SECONDS )
       .toEpochMilli() 

java.time

The modern approach in Java uses the java.time classes.

The Instant class represents a point on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.ofEpochMilli( 1_384_393_612_958L ) ;
Instant instantTrunc = instant.truncatedTo( ChronoUnit.SECONDS ) ;
long millis = instantTrunc.toEpochMilli() ;
like image 2
Basil Bourque Avatar answered Oct 16 '22 22:10

Basil Bourque