Search code examples
javadatedate-conversion

How to change the format of date in java


I have a string and i need to convert it to date in the "YYYY-mm-dd" format which i'm unable to do. I checked the similar post on stckoverflow but didnt help so i'm posting this query.

String stringDate = "Dec 13, 2013";

I need this to be convert to Date reportDate = 2013-12-13"; when i use simpledateformat i got unparsable date. Please help


Solution

  • Check this out:

        try {
            SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
            String stringDate = "Dec 13, 2013";
    
            Date date = format1.parse(stringDate);
    
            System.out.println(format2.format(date));
        } catch (ParseException exp) {
            // Take appropriate action
        }
    

    Output: 2013-12-13