将时区从字符串转换为 UTC (JODA TIME)

Converting Time Zones from a String to UTC (JODA TIME)

我在数据库中存储了 UTC 时间戳。当我检索到该 UTC 时间戳时,我将其转换为一个字符串。我想获取该 UTC 时间戳字符串并使用 Joda Time 将其转换为设备的本地时间。任何可以帮助解决这个问题的人。将不胜感激!这是我现在正在做的事情:

                String date = ""+ds.child("datecreated").getValue();

                DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

                DateTime dt = formatter.parseDateTime(date);

                DateTime dt2 = new DateTime(dt).toDateTime(DateTimeZone.getDefault());

                String personalDate = dt2.toString();

                dateTV.setText(personalDate);

                System.out.println("THIS IS THE FIRST TIME: " + dt + "THIS IS THE SECOND TIME: " + dt2); 

问题是,当我将它转换为当地时间时,它给我的时间完全相同,这是不应该的,因为它存储在 UTC 中,而我正在转换为东部标准时间是我的 phone 的默认值。

您缺少的部分是,正如 JavaDoc 所述,DateTime 对象在内部由 "milliseconds from the Java epoch of 1970-01-01T00:00:00Z."

的数量表示

因此,DateTime 没有时区。表示同一时刻的两个 DateTime 对象完全相同,无论您从中解析它的字符串中表示的时区如何。

只有日期时间 "has" 格式化时的时区。 当你格式化它时,你会得到一个带有你请求的时区的字符串,并且时间表示会相应地调整。

这两个日期(dt 和 d2)对你来说看起来一样的原因是你没有格式化它们(你使用了它们的隐式 "toString()" 方法),所以两个日期都用你当地的时区格式化了.

为了表明评论中的安德烈亚斯一语中的:我 运行 以下片段在 America/Coral_Harbour 时区(因为我不知道你的确切时区,东部标准时间被用于几个地方(尽管在 3 月 8 日东部夏令时间开始后更少)。

    String date = "2020-03-12T01:23:45.678+0000";

    System.out.println("This is the string:      " + date); 

    DateTime dt = new DateTime(date);
    DateTime dt2 = new DateTime(dt).toDateTime(DateTimeZone.getDefault());

    System.out.println("This is the first time:  " + dt); 
    System.out.println("This is the second time: " + dt2); 

输出为:

This is the string:      2020-03-12T01:23:45.678+0000
This is the first time:  2020-03-11T20:23:45.678-05:00
This is the second time: 2020-03-11T20:23:45.678-05:00

比较前两行,注意在解析字符串时已经发生了从 UTC 到 EST 的转换。

顺便说一句,由于您的字符串采用 ISO 8601 格式,因此您无需指定任何格式器来解析它。 DateTime(Object) 构造函数接受它。但是在您的解析中发生了相同的转换。

您的代码中发生了什么?

重复引用 Andreas 的评论:

If the withOffsetParsed() has been called, then the resulting DateTime will have a fixed offset based on the parsed time zone. Otherwise the resulting DateTime will have the zone of this formatter, but the parsed zone may have caused the time to be adjusted.

所以你的格式化程序有你设备的默认时区,因此也有你从解析中获得的 DateTime 对象。

因此,在创建 dt2 时,您正在从东部标准时间转换为东部标准时间,因此再次获得相同的日期时间。

Link: Documentation of DateTimeFormatter.parseDateTime()