java - 使用 joda time 获取自 2000 年以来的秒数

标签 java date datetime

我在 Oracle Java 8 中使用 JodaTime jar。我正在从固件设备接收数据包,它的开始时间是 2000 年 1 月 1 日的开始。我需要获取自 2000 年 1 月 1 日以来的秒数。数学看起来很简单,但出于某种原因,它给了我一个负值,这是 1999 年的某个时间,而不是当前时间:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;


public class TimeIssue {

    private DateTime currentTime = DateTime.now(DateTimeZone.UTC);
    private DateTime zeroPointTime = new DateTime(2000, 1, 1, 0, 0, DateTimeZone.UTC);

    private void checkTime(){
        System.out.println("current time: " + currentTime);     
        System.out.println("current time to secs: " + timetos(currentTime));
    }

    private int timetos(DateTime time){
        return (int)(time.getMillis() - zeroPointTime.getMillis())/1000;
    }

    public static void main(String[] args) {
        TimeIssue issue = new TimeIssue();
        issue.checkTime();
    }

}

输出:

current time: 2014-07-09T21:28:46.435Z
current time in seconds: -1304974
current time from seconds: 1999-12-16T21:30:26.000Z

我假设用 2000 年的毫秒时间减去当前的毫秒时间再除以 1000 会得到自 2000 年以来的当前时间(以秒为单位),但结果是一个负数。我可能做错了什么?

最佳答案

正如其他人所说,这是由于整数溢出。您可以只添加括号:

return (int)((time.getMillis() - zeroPointTime.getMillis())/1000);

但是使用 Duration 会更干净:

Duration duration = new Duration(zeroPointTime, currentTime);
return (int) duration.getStandardSeconds();

关于java - 使用 joda time 获取自 2000 年以来的秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664279/

相关文章:

Java Swing 按钮

java - 如何使用 Maven 添加 Postgresql jdbc 驱动程序 9.2-1003-jdbc3?

c++ - 如何在 C++ 中使用 MySQL 日期?

android-studio - Flutter:NoSuchMethodError: “The getter ' month'被调用为null是什么意思? (DateTime包)

java - 我如何计算重复的单词?

JavaFx-如果值全部相同,如何获取按钮数组索引

javascript - JS日期比较是如何工作的?

java - 静态方法总是同时返回

python - 使用 Selenium 抓取测试一致性

sql - Postgresql查询获取创建账号24小时内拥有少数属性的用户