Skip to content
Advertisement

Formatting ZonedDateTime for previous years

I am trying to format MM/dd/YY into 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?

Advertisement

Answer

    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:

2020-12-10T00:00Z

If you need the 00 seconds to be output too, use a second formatter:

    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

Points to take with you from here:

  • java.time, the modern Java date and time API, gives you all the functionality you need. Mixing in the old and troublesome date and time classes from Java 1.0 and 1.1 is an overcomplication at best.
  • 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. Instead I use 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. Instead date.atStartOfDay().atOffset(ZoneOffset.UTC) gives you the time at the start of day in UTC.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement