如何将当前时间戳以毫秒为单位四舍五入到秒?
如果这是以毫秒为单位的当前时间戳,我有 -
1384393612958
如果我四舍五入到最接近的秒,那会是这样吗?
Time in MS rounded off to nearest Second = 1384393612000
我可能需要在 Java 和 C++ 中都这样做。
如何将当前时间戳以毫秒为单位四舍五入到秒?
如果这是以毫秒为单位的当前时间戳,我有 -
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
基本上你想使用一个整数,除以一千(减少毫秒),然后乘以千,得到毫秒值四舍五入到秒。
在 Java 中,你可以使用 Calendar 来做这样的事情:
Calendar cal = Calendar.getInstance().setTimeInMillis(millisec);
int seconds = cal.get(Calendar.SECONDS);
或者(也可以为 C++ 工作)你可以这样做:
int sec = ((millisec + 500) / 1000);
添加 500 毫秒可让您正确舍入数字。
Instant.ofEpochMilli( 1_384_393_612_958L )
.truncatedTo( ChronoUnit.SECONDS )
.toEpochMilli()
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 = '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"
在 javascript 中,使用moment.js库:
moment(timestamp).startOf('second')