Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting wrong month when using SimpleDateFormat.parse

In my programm there is a very strange problem. Here you can see String birthday and Log to check it:

birthday = String.valueOf(birthYear) + "-" + String.valueOf(birthMonth) + "-" + String.valueOf(birthDay);
Log.i(TAG, "Birthday: " + birthday)

Then I put it to SimpleDateFormat and check it with the Log:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");

Date birthDate = sdf.parse(birthday);
Log.i(TAG, "Birth date  : " + birthDate);

And then in Logcat I have:

I/App﹕ Birthday: 1999-10-15
I/App﹕ Birth date: Fri Jan 15 00:10:00 GMT+04:00 1999

So as you see in the date it is Jan, but in the String it is 10 so date should look like:

Fri Nov 15 00:10:00 GMT+04:00 1999

Where is my mistake?

P.S I think my question is somehow connected with Getting wrong data when using SimpleDateFormat.parse()

like image 636
Sergius Avatar asked Jun 10 '14 13:06

Sergius


People also ask

How do I change date format in SimpleDateFormat?

String date_s = " 2011-01-18 00:00:00.0"; SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); Date date = dt. parse(date_s); SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd"); System. out. println(dt1.

Is SimpleDateFormat thread-safe True or false?

Java's SimpleDateFormat is not thread-safe, Use carefully in multi-threaded environments. SimpleDateFormat is used to format and parse dates in Java. You can create an instance of SimpleDateFormat with a date-time pattern like yyyy-MM-dd HH:mm:ss , and then use that instance to format and parse dates to/from string.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.


2 Answers

Use:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Use MM for month, mm for minutes as stated by documentation...

If you want to print a Date in a specific format, you should use:

 sdf.format(birthday)

or another SimpleDateFormat if you want to pring it in a different format...

like image 53
BobTheBuilder Avatar answered Sep 17 '22 20:09

BobTheBuilder


I faced the same issue and I found the error now. We should use MM for month, mm for minutes and dd for day. Using DD changed my date to wrong month, so I used dd for day and so final format I used is yyyy-MM-dd.

like image 25
Ayaz Qureshi Avatar answered Sep 17 '22 20:09

Ayaz Qureshi