forcey123 forcey123 - 3 months ago 10
Java Question

Java Date() giving the wrong date

I've got a simple method that should get the current date, put it into a certain format and then return it as a String. Up to this point it's been fine (last tried it on about 31st Jan) but for some reason when I tried it today it returns the String "2013-02-43".

Now obviously there aren't 43 days in February and I have no idea why it's returning this. I've searched everywhere I can for a solution but none of them seem to fit the specific problem I am having. Here is the code:

public String getDate(){
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
Date date = new Date();

return dateFormat.format(date);
}


Just for the record I've tried using Calendar.getInstance() etc. with the same result. Interestingly when I try

get(Calendar.DAY_OF_MONTH)


it comes back with 12, so somewhere the numbers are right but something's going wrong in between.

Thanks

Answer

DD means Day of Year, while dd means Day of Month. You want yyyy-MM-dd (case-sensitive).

public String getDate(){
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();

    return dateFormat.format(date);
}
Comments