如何将时间戳(以毫秒为单位)四舍五入到最接近的秒

How to round off timestamp in milliseconds to nearest seconds?

本文关键字:为单位 四舍五入 最接近 时间戳      更新时间:2023-10-16

如何将当前时间戳从毫秒四舍五入到秒?

如果这是我的当前时间戳(以毫秒为单位)-

1384393612958

如果我四舍五入到最接近的秒,会是这样吗?

Time in MS rounded off to nearest Second = 1384393612000

我可能需要在Java和C++中都这样做。

如果您使用的是Python:

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

基本上,你想使用一个整数,除以一千(去掉毫秒),然后乘以一千,得到四舍五入到秒的ms值。

在Java中,您可以使用Calendar来执行以下操作:

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

或者(也可以为C++工作)你可以做:

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

加500毫秒可以使数字正确地四舍五入。

tl;dr

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

java.time

Java中的现代方法使用Java.time类。

Instant类以UTC表示时间线上的一个点,分辨率为纳秒。

Instant instant = Instant.ofEpochMilli( 1_384_393_612_958L ) ;
Instant instantTrunc = instant.truncatedTo( ChronoUnit.SECONDS ) ;
long millis = instantTrunc.toEpochMilli() ;
This is needed to convert java date object to mysql datetime formatted string in sql queries.

转换:

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();

实际查询字符串包含:

createdOn="+新的SimpleDateFormat("yyyy-MM-dd HH:MM:ss").format(roundedCreatedOn)+"

在javascript中,使用moment.js库:

moment(timestamp).startOf('second')