如何将时间戳(以毫秒为单位)四舍五入到最接近的秒
How to round off timestamp in milliseconds to nearest seconds?
如何将当前时间戳从毫秒四舍五入到秒?
如果这是我的当前时间戳(以毫秒为单位)-
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')
相关文章:
- 以天C++为单位的两个时间戳之间的差异
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 编写以 C++ 为单位返回值的函数
- 以C++为单位进行运行长度编码
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- arr[n] 是否以 C++ 为单位打印数组的长度?
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 以 C++ 为单位具有输出限制的排列
- 以 GDB 为单位指定浮点精度
- 整数数据如何以位为单位存储在内存中?不是右对齐吗?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 指针引用的生存期(以 C++为单位)
- 以字符为单位设置控制台大小
- 获取嵌套 stl 容器的大小(以字节为单位)
- 有没有一种 STL 方法可以找到字符串的所有排列,给出一个以 C++ 为单位的大小?
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 如何将时间戳(以毫秒为单位)四舍五入到最接近的秒
- 以C++为单位四舍五入平均值的最简单方法