使用joda时间获取自2000年以来的秒数

Joh*_*ino 5 java datetime date

我正在使用JodaTime jar和Oracle Java 8.我正在接收来自固件设备的数据包,它的开始时间是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();
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

current time: 2014-07-09T21:28:46.435Z
current time in seconds: -1304974
current time from seconds: 1999-12-16T21:30:26.000Z
Run Code Online (Sandbox Code Playgroud)

我假设从2000年时间减去当前时间(以毫秒为单位),以毫秒为单位除以1000将得出自2000年以来的当前时间(以秒为单位),但它给出了一个负数.我可能做错了什么?

Jon*_*eet 7

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

return (int)((time.getMillis() - zeroPointTime.getMillis())/1000);
Run Code Online (Sandbox Code Playgroud)

但使用起来会更干净Duration:

Duration duration = new Duration(zeroPointTime, currentTime);
return (int) duration.getStandardSeconds();
Run Code Online (Sandbox Code Playgroud)