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



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

例:

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

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

DateTime dtUtcTs = new DateTime(utcTs);

有没有办法强制日期时间将字符串时间戳读取为 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)
}
}

下面是我看到的输出,我的应用程序服务器在 CST 区域中

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

使用 Joda Time 版本 2.9.1

你可以只使用DateTime构造函数的重载,它需要一个DateTimeZone

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

最新更新