Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting 1 day off when using parseDateTime in joda time

I am having a problem using the parseDateTime method in joda time. When I try to parse the date below, the result is one day off. I know there is already a similar thread about this, and I know that if your dayOfWeek and dayOfMonth are mismatched, it prioritizes the dayOfWeek. But my date is valid -- I have checked that february 22 falls on a Friday. But when I parse it, I am getting thursday, february 21. Here is the code:

DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");
DateTimeFormatter MYfmt = DateTimeFormat.forPattern("yyyy-MM-dd");

String date ="Fri, 22 Feb 2013 00:00:00 +0000";
    DateTime datetime = NBSfmt.parseDateTime(date);
            System.out.println(datetime.toString());

And here is the output: 2013-02-21T19:00:00.000-05:00

Anyone have any idea what is going on here? Any insight would be greatly appreciated. Thanks, Paul

like image 987
Paul Avatar asked Dec 06 '25 07:12

Paul


1 Answers

This is caused by your timezone. You define it in +0000 but then you're viewing it in -05:00. That makes it appear one day before. If you normalize it to UTC, it should be the same.

Try this code, as evidence:

package com.sandbox;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Sandbox {

    public static void main(String[] args) {
        DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");

        String date = "Fri, 22 Feb 2013 00:00:00 -0500";
        DateTime datetime = NBSfmt.parseDateTime(date);
        System.out.println(datetime.toString());
    }

}

For you, this should show the "right day". But for me, it shows 2013-02-21T21:00:00.000-08:00 because I'm in a different timezone than you. The same situation is happening to you in your original code.

Here's how you can print the string out in UTC:

package com.sandbox;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Sandbox {

    public static void main(String[] args) {
        DateTimeFormatter NBSfmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z");

        String date = "Fri, 22 Feb 2013 00:00:00 +0000";
        DateTime datetime = NBSfmt.parseDateTime(date);
        System.out.println(datetime.toDateTime(DateTimeZone.UTC).toString());
    }

}

This prints 2013-02-22T00:00:00.000Z.

like image 194
Daniel Kaplan Avatar answered Dec 07 '25 20:12

Daniel Kaplan