Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get number of seconds since year 2000 using joda time

I am using JodaTime jar with Oracle Java 8. I am receiving packets from a firmware device and its beginning of time is beginning of day of January 1, 2000. I need to get the number of second since January 1, 2000. The math seems simple but for some reason it is giving me a negative value, which comes out to a time in the year 1999, rather than current time:

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();
    }

}

output:

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

I would assume subtracting current time in milliseconds from year 2000 time in milliseconds and dividing by 1000 would give me the current time in seconds since 2000, but it is giving me a negative number. What might I be doing wrong?

like image 714
JohnMerlino Avatar asked Jul 09 '14 21:07

JohnMerlino


1 Answers

As others have said, this is due to integer overflow. You can just add brackets:

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

But it would be cleaner to use Duration:

Duration duration = new Duration(zeroPointTime, currentTime);
return (int) duration.getStandardSeconds();
like image 111
Jon Skeet Avatar answered Oct 31 '22 16:10

Jon Skeet