-2

In my application i want to change date format. In my application getting the date like this 04/07/20. But in my application I want to display like this 07, April 20. For that I using the following code

try {
       String date="04/07/20"
       SimpleDateFormat spf = new SimpleDateFormat("mm/dd/yy")
       Date newDate = spf.parse(date);
       SimpleDateFormat new_spf = new SimpleDateFormat("dd MMMM, yy");
       date = new_spf.format(newDate);
        System.out.println(date);
      } catch (Exception e) {

        }

But the output getting like this 07 January, 20, But I need 07 April, 20.

Can you share the suggestions for this one.

Thanks In Advance.

rams
  • 1,558
  • 7
  • 25
  • 48
  • Your requirement nd your result seems similar! How you want the result? Whats the difference in Jan and April dates? – Prajwal Waingankar Apr 07 '20 at 11:38
  • here getting January instead of April. The actual date is 04/07/20 if I changed the date format date should be 07 April, 20, but the output getting 07 January, 20. – rams Apr 07 '20 at 11:43
  • Month displaying wrong – rams Apr 07 '20 at 11:44
  • 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 `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 11 '20 at 14:43

1 Answers1

3

You mixed:

mm  =  minutes

with

MM  =  months

So you have to change from:

SimpleDateFormat spf = new SimpleDateFormat("mm/dd/yy");

in to:

SimpleDateFormat spf = new SimpleDateFormat("MM/dd/yy");

When you print before changes:

System.out.println(newDate);

You will receive:

 Tue Jan 07 00:04:00 WET 2020
               /\
               ||
               ||
          your minutes

Full working example

(with better naming)

try {
    String inputDate = "04/07/20";
    SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yy");

    Date parsedDate = inputFormat.parse(inputDate);
    SimpleDateFormat outputFormat = new SimpleDateFormat("dd MMMM, yy");

    inputDate = outputFormat.format(parsedDate);
    System.out.println(inputDate);
} catch (Exception e) {
    e.printStackTrace();
}
Community
  • 1
  • 1
Boken
  • 4,825
  • 10
  • 32
  • 42