简体   繁体   English

如何将 EDT 中的日期字符串转换为 UTC 日期?

[英]How to convert date string in EDT to UTC date?

I am reading data from upstream system and it returns the date in string format like this,我正在从上游系统读取数据,它以这样的字符串格式返回日期,

String dateFromUpstream = 11-14-2022 10:41:12 EDT

Now, I want to convert this string to a date format of UTC timezone and then store it into my entity.现在,我想将此字符串转换为 UTC 时区的日期格式,然后将其存储到我的实体中。

I tried the following way,我尝试了以下方式,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss z");
LocalDateTime date = ZonedDateTime.parse(dateFromUpstream, formatter).toLocalDateTime().atZone(ZoneId.of("UTC"));

But this doesn't change the date to UTC timezone.但这不会将日期更改为 UTC 时区。 It still gives me the same date with UTC instead of EDT at the end of the string.它仍然在字符串末尾为我提供与 UTC 而不是 EDT 相同的日期。

Anyone know how I can do this and then store into an entity?任何人都知道我该怎么做然后存储到一个实体中?

Parse the given date-time string into a ZonedDateTime with the corresponding DateTimeFormatter and then convert the resulting ZonedDateTime into an Instant or another ZonedDateTime corresponding to UTC, using ZonedDateTime#withZoneSameInstant .使用相应的DateTimeFormatter将给定的日期时间字符串解析为ZonedDateTime ,然后使用ZonedDateTime#withZoneSameInstant将生成的ZonedDateTime转换为Instant或与 UTC 对应的另一个ZonedDateTime

Demo :演示

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String dateFromUpstream = "11-14-2022 10:41:12 EDT";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-uuuu HH:mm:ss z", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(dateFromUpstream, dtf);
        Instant instant = zdt.toInstant();
        System.out.println(instant);

        // Or get a ZonedDateTime at UTC
        ZonedDateTime zdtUTC = zdt.withZoneSameInstant(ZoneOffset.UTC);
        System.out.println(zdtUTC);

        // If you want LocalDateTime
        LocalDateTime ldt = zdtUTC.toLocalDateTime();
        System.out.println(ldt);
    }
}

See this code run at Ideone.com .请参阅在 Ideone.com 运行的这段代码

Output : Output :

2022-11-14T15:41:12Z
2022-11-14T15:41:12Z
2022-11-14T15:41:12

Learn more about the modern Date-Time API from Trail: Date Time .Trail:Date Time了解有关现代日期时间 API 的更多信息。


Note : As suggested by Basil Bourque , you can convert the parsed date-time into an OffsetDateTime at UTC as shown below:注意:根据Basil Bourque的建议,您可以将解析的日期时间转换为 UTC 的OffsetDateTime ,如下所示:

OffsetDateTime odtUTC = zdt.toOffsetDateTime()
                           .withOffsetSameInstant(ZoneOffset.UTC);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM