Getting wrong month when using SimpleDateFormat.parse

前端 未结 3 1507
长情又很酷
长情又很酷 2020-11-27 23:59

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

birthday = String.valueOf(bir         


        
相关标签:
3条回答
  • 2020-11-28 00:10

    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.

    0 讨论(0)
  • 2020-11-28 00:19

    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.

    0 讨论(0)
  • 2020-11-28 00:27

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

    0 讨论(0)
提交回复
热议问题