使用 DateTime class joda 时间库将 UTC 中的字符串时间戳读取为 UTC 时间

Reading string timestamp in UTC as UTC time using DateTime class joda time library

我在字符串中有一个时间戳,它在 UTC 时区,我想使用 joda 时间库中的 DateTime 按 UTC 时区读取它。

示例:

String utcTs = "2016-06-01T14:46:22.001Z";

当我在 stmt. 下面尝试时,DateTime 正在读取它并转换为应用程序所在的服务器时区 运行!!

DateTime dtUtcTs = new DateTime(utcTs);

有没有办法强制 DateTime 将字符串时间戳读取为 UTC?

我的应用程序服务器在 CST 中,当像下面这样使用 SOP stmt 打印日期时,我观察的是 CST 时间而不是 UTC!

System.out.println(dtUtcTs) ==> 给我应用所在服务器的日期 运行!!

非常感谢!!

import org.joda.time.DateTime;

public class TestClass {

public static void main(String[] args) {

String utcTs = "2016-06-01T14:46:22.001Z";
DateTime dtUtcTs = new DateTime(utcTs);

System.out.println(dtUtcTs)

}
}

下面是我看到的输出,我的应用程序服务器是 in CST zone

2016-06-01T09:46:22.001-05:00

使用 joda 时间版本 2.9.1

您可以只使用带有 DateTimeZone:

DateTime 构造函数的重载
DateTime dtUtcTs = new DateTime(utcTs, DateTimeZone.UTC);

另一种选择是使用 DateTimeFormatter,这样您就可以准确地指定您期望的格式和您想要的时区。

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2016-06-01T14:46:22.001Z";
        DateTime dt = ISODateTimeFormat.dateTime()
            .withZone(DateTimeZone.UTC)
            .parseDateTime(text);
        System.out.println(dt);
    }
}