6

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++.

AKIWEB
  • 19,008
  • 67
  • 180
  • 294

5 Answers5

9

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.

Suman
  • 9,221
  • 5
  • 49
  • 62
4

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.

Luca S.
  • 1,132
  • 2
  • 16
  • 31
2

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() ;
Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
This is needed to convert java date object to mysql datetime formatted string in sql queries.

Conversion:

Calendar cal = Calendar.getInstance();
cal.setTime(this.id.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
  System.out.println("Round off milliseconds to seconds");
  cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}
Date roundedCreatedOn = cal.getTime();

Actual query string contains:

createdOn = '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"

AravindR
  • 677
  • 4
  • 11
  • without this, mysql's timestamp column did not match the query generated using new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn) as SimpleDateFormat just drops additional milliseconds. – AravindR Nov 15 '17 at 08:20
0

In javascript, using the moment.js library:

moment(timestamp).startOf('second')
James Gentes
  • 7,528
  • 7
  • 44
  • 64