Search code examples
javadate-formatsimpledateformatjdatechooser

Error when converting date format to another


I have a String in format "YYYY-MM-dd" and i want convert this into "MMM dd, yyyy" format.

I used bellow code to do this; But when i convert "2014-11-18" the output is this "Sun Dec 29 00:00:00 IST 2013"

How can I solve this?

DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
String P_date="2014-11-18"
Date test1 = new SimpleDateFormat("YYYY-MM-dd").parse(P_date);

String converted_date=target.format(test1);
Date test=target.parse(converted_date);

Solution

  • The y (lowercase Y) format means "year". Y (uppercase Y) you were using means "WeekYear". Just use y and you should be OK:

    DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
    String P_date="2014-11-18";
    Date test1 = new SimpleDateFormat("yyyy-MM-dd").parse(P_date);
    
    String converted_date=target.format(test1);
    Date test=target.parse(converted_date);