Search code examples
javadateparsingtimesimpledateformat

Changing date formats


I have the following code:

// OLD DATE
String date = "Mon, 06/07";

DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = date.substring(date.length() - 5);
Date dateOld;
try {
    dateOld = df.parse(strDate);
} catch (Exception e) {
    e.printStackTrace();
}
String dateStr = df.format(dateOld);
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime dateNew = ZonedDateTime.now().with(monthDay);

// NEW DATE
System.out.println(dateNew.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'")));

Basically what I am trying to do is change Mon, 06/07 format to this format 2021-06-07T00:00:00Z.

What I have works, but it is really terrible. What would be a better way of doing it?


Solution

  • This is a little tricky as you need to make some assumptions

    • The year, as it's not specified in the original format
    • TimeZone, as it's not specified at all (the final output seems to point to UTC)

    The first thing your need to do, is parse the String input into a LocalDate (you could just go straight to ZonedDate, but this is where I started)

    String date = "Mon, 06/07";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .appendPattern("E, M/d")
            .parseDefaulting(ChronoField.YEAR, 2021)
            .toFormatter(Locale.US);
    
    LocalDate ld = LocalDate.parse(date, parseFormatter);
    

    Then you need to convert that to LocalDateTime

    LocalDateTime ldt = ld.atStartOfDay();
    

    And then, to a ZonedDateTime. Here' I've assumed UTC

    //ZoneId zoneId = ZoneId.systemDefault();
    //ZonedDateTime zdt = ldt.atZone(zoneId);
    OffsetDateTime zdt = ldt.atOffset(ZoneOffset.UTC);
    

    And finally, format the result to your desired format

    String formatted = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    System.out.println(formatted);
    

    Which, for me, prints...

    2021-06-07T00:00:00Z
    

    A lot of time and effort has gone into the new Date/Time APIs and you should make the time to try and learn them as best you can (I'm pretty rusty, but with a little tinkering, got to a result)

    Maybe start with Date/Time trails