Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date() giving the wrong date [duplicate]

Tags:

java

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

like image 909
forcey123 Avatar asked Nov 28 '22 21:11

forcey123


2 Answers

DD means Day of Year, while dd means Day of Month. Also, Y means Week Year, while y means Year. 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);
}
like image 86
Chris Cashwell Avatar answered Dec 15 '22 02:12

Chris Cashwell


Capital D in a DateFormat is date in year. You want date in month:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
like image 25
Dave DeCaprio Avatar answered Dec 15 '22 02:12

Dave DeCaprio