简体   繁体   English

如何将日期字符串转换为 UTC 日期 object?

[英]How to convert Date string into UTC Date object?

I'm learning Java and come across this issue.我正在学习 Java 并遇到这个问题。 I have a date string with the given format.我有一个给定格式的日期字符串。

String dbTime = "01/01/1998 12:30:00";
final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";

Now I wanted to initialize/create a Date object of UTC timezone.现在我想初始化/创建一个UTC时区的日期object。 For this, I have tried below code为此,我尝试了以下代码

    SimpleDateFormat sdfAmerica = new SimpleDateFormat(DATE_FORMAT);
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    sdfAmerica.setTimeZone(utcTimeZone);

    String sDateInAmerica = sdfAmerica.format(date); // Convert to String first
    Date dateInAmerica = new Date();
    try {
        dateInAmerica = formatter.parse(sDateInAmerica); // Create a new Date object
    } catch (ParseException e) {
        e.printStackTrace();
    }

This will convert the time into UTC instead of just creating a date object.这会将时间转换为 UTC,而不仅仅是创建日期 object。

01/02/1998 23:00:00

Now I'm confused as to which is the correct approach to convert the time.现在我很困惑哪种是转换时间的正确方法。 I have time in string format and I have to convert it into different formats mainly UTC to PST or PST to UTC.我有时间使用字符串格式,我必须将其转换为不同的格式,主要是 UTC 到 PST 或 PST 到 UTC。

After some research, I found this tutorial but was unable to get the expected output.经过一番研究,我找到了本教程,但无法获得预期的 output。

The java.util.Date class is not optimal to start with. java.util.Date class 不是最佳选择。 While it looks like a full date from the outside, it actually only represents a timestamp without storing actual timezone information.虽然从外部看起来像是一个完整的日期,但它实际上只表示一个时间戳,而没有存储实际的时区信息。

On Java 8 and later I'd suggest to stick with the better designed java.time.* classes.在 Java 8 及更高版本上,我建议坚持使用设计更好的 java.time.* 类。

    String dbTime = "01/01/1998 12:30:00";
    String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";

    // parsed date time without timezone information
    LocalDateTime localDateTime = LocalDateTime.parse(dbTime, DateTimeFormatter.ofPattern(DATE_FORMAT));

    // local date time at your system's default time zone
    ZonedDateTime systemZoneDateTime = localDateTime.atZone(ZoneId.systemDefault());

    // value converted to other timezone while keeping the point in time
    ZonedDateTime utcDateTime = systemZoneDateTime.withZoneSameInstant(ZoneId.of("UTC"));

    // timestamp of the original value represented in UTC
    Instant utcTimestamp = systemZoneDateTime.toInstant();


    System.out.println(utcDateTime);
    System.out.println(utcTimestamp);

As you can see from the names alone there are different classes for different use-cases of dates.正如您仅从名称中所看到的,对于不同的日期用例,有不同的类。

java.time.LocalDateTime for example only represents a date and time without a specific timezone context and therefore can be used to parse your string value directly.例如 java.time.LocalDateTime 仅表示没有特定时区上下文的日期和时间,因此可用于直接解析您的字符串值。

To convert timezones, you first have to convert into the a ZonedDateTime, which accepts date, time and timezone.要转换时区,您首先必须转换为 ZonedDateTime,它接受日期、时间和时区。 I've intialized the sample on "systemDefault", as on most smaller apps you can use the JVM and OS'es default value to assume the current timezone.我已经在“systemDefault”上初始化了示例,因为在大多数较小的应用程序上,您可以使用 JVM 和操作系统的默认值来假设当前时区。 You could also use ZoneId.of("America/Los_Angeles") directly if you want to make sure the value is interpreted as pacific time.如果您想确保该值被解释为太平洋时间,您也可以直接使用 ZoneId.of("America/Los_Angeles") 。

This value can be converted into another ZonedDateTime in another timezone, eg UTC.该值可以转换为另一个时区中的另一个 ZonedDateTime,例如 UTC。

For UTC especially you could also use the Instant class, which represents only a UTC timestamp and can also be used as a basis for most other types特别是对于 UTC,您还可以使用 Instant class,它仅代表 UTC 时间戳,也可以用作大多数其他类型的基础

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

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