Search code examples
javadatesimpledateformat

Change date from MM/dd to yyyy-MM-dd'T'HH:mm:ss.SSZ in Java


I have a String that formatted MM/dd. I would like to convert it to a Date in format yyyy-MM-dd'T'HH:mm:ss.SSZ.

DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = "06/05";
Date date = new Date();
date = df.parse(strDate);

This makes it a Date, but in the original format.

System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ").format(date));

This returns the correct month and day, but nopthing else.

1970-06-05T00:00:00.00-0400

Any idea how I can make it return

CURRENT_YEAR-06-05TCURRENT_TIME

Solution

  • In the question, the date format pattern indicates a desire for 2-digit fractional seconds. SimpleDateFormat cannot do that.

    The newer Java 8 Time API can, and you should be using that anyway.

    If you're running on Java 6 or 7, get the ThreeTen-Backport library.

    To parse a MM/dd formatted string and get a full timestamp with current year and time-of-day, in the default time zone, use the following code:

    String strDate = "06/05";
    MonthDay monthDay = MonthDay.parse(strDate, DateTimeFormatter.ofPattern("MM/dd"));
    ZonedDateTime date = ZonedDateTime.now().with(monthDay);
    System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ")));
    

    Sample Output

    2020-06-05T14:52:48.45-0400