简体   繁体   English

格式化前几年的 ZonedDateTime

[英]Formatting ZonedDateTime for previous years

I am trying to format MM/dd/YY into uuuu-MM-dd'T00:00:00Z .我正在尝试将MM/dd/YY格式化为uuuu-MM-dd'T00:00:00Z

I have the following code.我有以下代码。

String dateTime = "12/10/20";
DateFormat df = new SimpleDateFormat("MM/dd/yy");
Date date;
date = df.parse(dateTime); // Thu Dec 10 00:00:00 EST 2020
String dateStr = df.format(date); // 12/10/20
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd/yy")); // --12-10
ZonedDateTime newDate = ZonedDateTime.now().with(monthDay); // 2021-12-10T12:34:21.214-05:00[US/Eastern]
String formattedDate = newDate.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'"));

The issue with is that dates from previous years (like in this example) are being returned as current year.问题是前几年的日期(如本例中)被作为当前年份返回。

How can I use the same format but take the year into consideration?我如何使用相同的格式但考虑到年份?

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yy");
    
    String dateTime = "12/10/20";
    LocalDate date = LocalDate.parse(dateTime, formatter);
    OffsetDateTime  newDateTime = date.atStartOfDay().atOffset(ZoneOffset.UTC);
    
    System.out.println(newDateTime);

Output this far: Output 到目前为止:

2020-12-10T00:00Z 2020-12-10T00:00Z

If you need the 00 seconds to be output too, use a second formatter:如果您也需要 00 秒为 output,请使用第二个格式化程序:

    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
    String formattedDateTime = newDateTime.format(outputFormatter);
    System.out.println(formattedDateTime);

2020-12-10T00:00:00Z 2020-12-10T00:00:00Z

Points to take with you from here:从这里随身携带的要点:

  • java.time, the modern Java date and time API, gives you all the functionality you need. java.time,现代 Java 日期和时间 API,为您提供所需的所有功能。 Mixing in the old and troublesome date and time classes from Java 1.0 and 1.1 is an overcomplication at best.混合来自 Java 1.0 和 1.1 的旧且麻烦的日期和时间类充其量是过于复杂了。
  • A MonthDay , as the name says, is a month and day of month, so does not include a year, which is where you lose it.顾名思义, MonthDay是一个月和一个月中的一天,因此不包括一年,这是您丢失它的地方。 Instead I use LocalDate .相反,我使用LocalDate
  • ZonedDateTime.now() gives you the current date and time in your own time zone, which is not what you need when you want a result in UTC. ZonedDateTime.now()为您提供您自己时区的当前日期和时间,当您想要 UTC 的结果时,这不是您所需要的。 Instead date.atStartOfDay().atOffset(ZoneOffset.UTC) gives you the time at the start of day in UTC.取而代之date.atStartOfDay().atOffset(ZoneOffset.UTC)以 UTC 为您提供一天开始的时间。

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

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