简体   繁体   English

如何将时间戳以毫秒为单位舍入到最接近的秒数?

[英]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++. 我可能需要在Java和C ++中都这样做。

If you are using Python: 如果您使用的是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. 基本上你想要使用一个整数,除以一千(以减去毫秒),然后乘以千来得到ms值四舍五入到秒。

In Java you can use Calendar to something like this: 在Java中,您可以将Calendar用于以下内容:

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

Alternatively (and can work for C++ too) you can do: 或者(也可以用于C ++)你可以这样做:

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

adding 500 ms allows you to round the number properly. 添加500毫秒可以正确舍入数字。

tl;dr TL;博士

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

java.time java.time

The modern approach in Java uses the java.time classes. Java中的现代方法使用java.time类。

The Instant class represents a point on the timeline in UTC with a resolution of nanoseconds. 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.

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)+ "'" createdOn ='“+ new SimpleDateFormat(”yyyy-MM-dd HH:mm:ss“)。format(roundedCreatedOn)+”'“

在javascript中,使用moment.js库:

moment(timestamp).startOf('second')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM