Sergius
Sergius

Reputation: 531

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()

Upvotes: 7

Views: 6568

Answers (3)

Ayaz Qureshi
Ayaz Qureshi

Reputation: 23

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.

Upvotes: 2

Anonymous
Anonymous

Reputation: 86280

ThreeTenABP

I should like to provide the 2017 answer. For Android, first get the ThreeTenABP library. Instructions are in this question: How to use ThreeTenABP in Android Project. Then the rest is as straightforward as:

    LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
    System.out.println("Birth date  : " + birthDate);

This prints:

Birth date  : 1999-10-15

When you’ve got the year, month and day of month as numbers, there is no need to do any parsing, that would just complicate things.

ThreeTenABP is the backport of java.time or JSR-310, the modern Java date and time API, to Android Java 7. If you are using Java 8 or later, java.time is built-in. There is also a backport for (non-Android) Java 6 and 7: ThreeTen Backport.

Upvotes: 0

BobTheBuilder
BobTheBuilder

Reputation: 19284

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...

Upvotes: 23

Related Questions