我在 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/