简体   繁体   中英

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.

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

LocalDate has no time component, so if the times are on the same day, they're effectively turned into the same time. Instead, just diff the DateTimes as they are;

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 )

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. Instead, use krzydyn's answer if it's just a time diff between UTC times.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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