Get seconds since 2000 using Joda's time

I am using the JodaTime jar with Oracle Java 8. I receive packages from the firmware device and it starts on January 1, 2000. I need to get the second number from January 1, 2000. The math seems simple, but for some reason it gives me a negative value that comes out at that time in 1999, and not at the 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 suggest that it subtracts the current time in milliseconds since 2000 in milliseconds, and dividing by 1000 will give me the current time in seconds since 2000, but it gives me a negative number. What can i do wrong?

+4
source share
4 answers

, . :

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

Duration:

Duration duration = new Duration(zeroPointTime, currentTime);
return (int) duration.getStandardSeconds();
+6

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

int 1000.

long int int, .

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

int.

+2

- int

int long

~ ~ t22 >
946713600000

~

458229057398

-1332420848

int 2147483647

long

int, Jan 19 2068

+1
source

January 1, 2000 was approximately 946,684,800,000 milliseconds, which is about 458,257,821,000 million years ago. This number is greater than the number of milliseconds an int can hold (2,147,483,647). This means that your tide intwill lead to integer overflow , this is what you see.

+1
source

Source: https://habr.com/ru/post/1547834/


All Articles