Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert a date YYYY-MM-DD to DD-MMM-YYYY but the function always returns January as the month.

Tags:

java

date

I have the following function to convert date:

public String dateConvert(String D){

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-DD");
        SimpleDateFormat format2 = new SimpleDateFormat("dd-MMMM-yyyy");
        Date date = null;
        try {
            date = format1.parse(D);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String dateString = format2.format(date);
        dateString = dateString.replace("-", " "); 
        System.out.println(dateString);
        return ((dateString));
    }

However what ever date I pass to this, the month is always converted to January. I cant understand where I am going wrong!

like image 778
User3 Avatar asked Mar 22 '23 08:03

User3


1 Answers

Uppercase D is the day of the year, not the day of the month.

If you take any day of the month (1-31) and treat it as the day of the year, it will fall in January.

Use lowercase d for format1.

like image 166
paxdiablo Avatar answered Apr 06 '23 10:04

paxdiablo