2

我在 joda 时间使用 parseDateTime 方法时遇到问题。当我尝试解析下面的日期时,结果是休息一天。我知道已经有一个类似的线程,而且我知道如果你的 dayOfWeek 和 dayOfMonth 不匹配,它会优先考虑 dayOfWeek。但是我的日期是有效的——我已经检查过 2 月 22 日是星期五。但是当我解析它时,我得到了 2 月 21 日星期四。这是代码:

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

这是输出:2013-02-21T19:00:00.000-05:00

有人知道这里发生了什么吗?任何见解将不胜感激。谢谢,保罗

4

2 回答 2

4

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.

于 2013-06-14T20:53:40.427 回答
1

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.

于 2013-06-14T20:53:44.730 回答