javadatesimpledateformat

Convert Data format using SimpleDateFormat


I need to convert date format into NEW_FORMAT date format. I want to show like this June 28,2016 ,but its showing January irrespective of any month number I pass. Please check where I am missing..

public class DateClass {

        public static void main(String[] args)
        {
            final String OLD_FORMAT = "yyyy-mm-dd";
            final String NEW_FORMAT = "MMMM dd,yyyy";

            String oldDateString = "2016-06-28";
            String newDateString;

            SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
            Date d;
            try {
                d = sdf.parse(oldDateString);
                sdf.applyPattern(NEW_FORMAT);
                newDateString = sdf.format(d);
                System.out.println(""+newDateString);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

Solution

  • your OLD_FORMAT is wrong, it should be "yyyy-MM-dd". Here small m should be replaced by capital M, since small m represents minutes and M represents month of year, and while parsing using OLD_FORMAT, date is getting parsed wrongly.