简体   繁体   English

Joda-Time-两个日期之间的秒数

[英]Joda-Time - Number of seconds between two dates

My english is not perfect, but I hope you can understand me. 我的英语不太好,但我希望你能理解我。

I try to get the difference in seconds between two unix timestamps, but it's only return 0. 我试图得到两个unix时间戳之间以秒为单位的差异,但它仅返回0。

That's my code 那是我的代码

unixOnline = Long.valueOf(online);
unixOffline = Long.valueOf(offline);

DateTimeZone BERLIN = DateTimeZone.forID("Europe/Berlin");
DateTime dateTimeOnline = new DateTime(unixOnline * 1000L, BERLIN);
DateTime dateTimeOffline = new DateTime(unixOffline * 1000L, BERLIN);

int seconds = Seconds.secondsBetween(new LocalDate(dateTimeOnline), new LocalDate(dateTimeOffline)).getSeconds();
System.out.println("Seconds: " + seconds);

Edit: Online Timestamp: 1457536522 Offline Timestamp: 1457536642 编辑:在线时间戳:1457536522离线时间戳:1457536642

LocalDate has no time component, so if the times are on the same day, they're effectively turned into the same time. LocalDate没有时间成分,因此,如果时间在同一天,它们实际上将变成同一时间。 Instead, just diff the DateTimes as they are; 相反,只需按原样比较DateTimes即可;

int hours = Hours.hoursBetween(dateTimeOnline, dateTimeOffline).getHours();

(or in your case, since the difference is only 2 minutes, you'll only see the result with Minutes or Seconds ) (或者您的情况是,由于相差只有2分钟,因此您只能以MinutesSeconds查看结果)

EDIT: Since the question seems to have nothing to do with the time zone BERLIN which is in the code, this answer is a bit over complicated. 编辑:由于该问题似乎与代码中的时区BERLIN无关,因此此答案有点复杂。 Instead, use krzydyn's answer if it's just a time diff between UTC times. 如果只是UTC时间之间的时间差,请使用krzydyn的答案。

Since you already have timestamps in seconds it can be simple calculated by formula: 由于您已经有了以秒为单位的时间戳记,因此可以通过公式简单地进行计算:

 int hours = (t2-t1)/3600;

Or if you need fractions: 或者,如果您需要分数:

float hours = (t2-t1)/3600f;

Update: (maybe I got suggested by the answer :) So to get time diff in seconds is even simpler: 更新:(也许我得到了答案的建议:)因此,以秒为单位的时间差异更加简单:

long seconds = t2-t1;

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

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