【问题标题】:How to round off timestamp in milliseconds to nearest seconds?如何以毫秒为单位将时间戳四舍五入到最接近的秒数?
【发布时间】:2013-12-21 12:17:30
【问题描述】:

如何将当前时间戳以毫秒为单位四舍五入到秒?

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

1384393612958

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

Time in MS rounded off to nearest Second = 1384393612000

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

【问题讨论】:

    标签: java c++ timestamp milliseconds seconds


    【解决方案1】:

    在 javascript 中,使用 moment.js 库:

    moment(timestamp).startOf('second')
    

    【讨论】:

      【解决方案2】:

      tl;博士

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

      【讨论】:

        【解决方案3】:
        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)+ "'"

        【讨论】:

        • 如果没有这个,mysql 的时间戳列与使用 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn) 生成的查询不匹配,因为 SimpleDateFormat 只会减少额外的毫秒数。
        【解决方案4】:

        在 Java 中,你可以使用 Calendar 来做这样的事情:

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

        或者(也适用于 C++)你可以这样做:

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

        添加 500 毫秒可让您正确舍入数字。

        【讨论】:

        • 仅供参考,这段代码使用了麻烦的旧日期时间类,这些类现在是遗留的,被 java.time 类所取代。
        【解决方案5】:

        如果您使用的是 Python:

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

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

        【讨论】:

        • 从技术上讲,这是将数字截断到前一秒,而不是四舍五入到最近,这更像是1000 * ((old_number + 500) / 1000)...
        • @twalberg,虽然是真的,但 TrekkieTechie 的示例截断了数字。
        • @BrianS 嗯......我没有注意到,但你是对的......所以看起来 OP 不确定他们是否想要舍入或截断。
        • 在Python中你可以从头开始取整:int(round(time.time()))
        • 对于 Python 3,将 / 替换为 //
        猜你喜欢
        • 1970-01-01
        • 2021-12-11
        • 2018-06-03
        • 2018-05-27
        • 2014-12-12
        • 1970-01-01
        • 2011-03-28
        • 2018-10-25
        • 1970-01-01
        相关资源
        最近更新 更多