0

I have one function which takes input a string value like 3-2020. I want to parse this string as a date and change its format to something like March-2020 using SimpleDateFormat class. Here is the code I am using for this task:

public String getCurrentMonth(String day) throws ParseException {
    Date today = new SimpleDateFormat("MM-YYYY").parse(day);
    return new SimpleDateFormat("MMMM-YYYY").format(today);
}

but it is giving a very different output string. When the input provided as 4-2020, it returns value as December-2020. The today variable has a value Sun Dec 29 00:00:00 GMT+05:30 2019. There is a huge difference in the dates. Why is it happening? and how to solve this?

hawk
  • 39
  • 5
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `YearMonth` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 04 '20 at 11:45

2 Answers2

1

Please use this small y instead of Y

Date today = new SimpleDateFormat("MM-yyyy").parse("04-2020");
System.out.println(new SimpleDateFormat("MMMM-yyyy").format(today));
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

Y is the format for the week year. It looks like you intended to use y, which is the format for the year:

public String getCurrentMonth(String day) throws ParseException {
    Date today = new SimpleDateFormat("MM-yyyy").parse(day);
    return new SimpleDateFormat("MMMM-yyyy").format(today);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • exactly, it solved and cleared the meaning of notation with difference of `Y` and `y` – hawk Jul 04 '20 at 11:08