Paul
Paul

Reputation: 1176

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

Upvotes: 3

Views: 1342

Answers (2)

Daniel Kaplan
Daniel Kaplan

Reputation: 67360

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.

Upvotes: 5

zw324
zw324

Reputation: 27190

The timezone of yours is -5, and joda treats the input as UTC in the example. You can use withZone to get a new formatter if needed.

Upvotes: 1

Related Questions