-3

I was trying to convert date from yyyy-MM-dd format to yyyy-MM format, when I run the below code with the input "2012-10-22" it is giving me an output of 2012-JAN instead of 2012-OCT. any thoughts on where I am doing wrong?

  public static String dateFormatter(String presentDate)
     {
     String formattedDate = "";
     SimpleDateFormat tempFormat = new SimpleDateFormat("YYYY-MM-DD");
     SimpleDateFormat finalFormat = new SimpleDateFormat("YYYY-MMM");

     try {
        Date currentFormat = tempFormat.parse(presentDate);
        formattedDate = finalFormat.format(currentFormat);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    return formattedDate;
}
  • 1
    Case is very important for the SimpleDateFormat mask – Scary Wombat Oct 23 '17 at 02:51
  • 1
    As with all issues with `DateFormat`, consult the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) first. `Y` is *"Week year"* – MadProgrammer Oct 23 '17 at 02:56
  • FYI, this code uses troublesome old date-time classes that are now legacy, supplanted by the modern java.time classes. – Basil Bourque Oct 23 '17 at 14:56
  • Using java.time classes: `YearMonth.from( LocalDate.parse( "2012-10-22" ) ).format( DateTimeFormatter.ofPattern( "uuuu-MMM" , Locale.US ) )` ➢ `2012-Oct` See this [code run live at IdeOne.com](https://ideone.com/EULBmC) – Basil Bourque Oct 24 '17 at 00:32

2 Answers2

1

Change the first format to

SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");

as DD is the day in the year. 22 is definitely in January

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Use this

SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");

Instead of

SimpleDateFormat tempFormat = new SimpleDateFormat("YYYY-MM-DD");
Crammeur
  • 678
  • 7
  • 17