Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time Number of Days since Epoch

Tags:

java

jodatime

I have a problem whereby the number of days since epoch returned by Joda-Time library changes depending the time of the date I entered. If I enter 2012-05-14 22:00:00 and 2012-05-14 02:00:00 I would expect the same result since they are both on the same day. The following is my code.

        try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = sdf.parse("2013-05-03 07:00:00");
        Date date2 = sdf.parse("2013-05-03 23:30:00");


        MutableDateTime epoch = new MutableDateTime();
        epoch.setDate(0); //Set to Epoch time
        System.out.println("Epoch: " + epoch);
        Days days1 = Days.daysBetween(epoch, new MutableDateTime(date1.getTime()));
        Days days2 = Days.daysBetween(epoch, new MutableDateTime(date2.getTime()));
        System.out.println("1) Days Since Epoch: " + days1.getDays());
        System.out.println("2) Days Since Epoch: " + days2.getDays());
    } catch (ParseException e) {
        e.printStackTrace(); 
    }

Epoch: 1970-01-01T11:09:00.414+01:00
1) Days Since Epoch: 15827
2) Days Since Epoch: 15828

Does anyone have any idea what I'm doing wrong?

like image 371
Kros Avatar asked Oct 22 '22 10:10

Kros


1 Answers

OK found the problem (which was in front of my own eyes :)) ... the epoch I was getting was indeed starting from 1970-01-01 but not from the very first ms of that day.

I needed to add the following line to get it sorted:

epoch.setTime(0);
like image 146
Kros Avatar answered Oct 24 '22 03:10

Kros