简体   繁体   中英

Joda-Time Number of Days since Epoch

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?

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

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