java. text. Strange behavior in simpledateformat, expecting yyyymmdd to give yyyy MM DD

When using simpledateformat to parse strings to dates, I encountered a very strange behavior Consider the following unit tests:

@Test
public void testParse() throws ParseException
{
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    String dateStr = "2012-12-21";
    Date parsedDate = dateFormat.parse(dateStr);
    Calendar date = Calendar.getInstance();
    date.setTime(parsedDate);

    Assert.assertEquals(2012,date.get(Calendar.YEAR));
    Assert.assertEquals(11,date.get(Calendar.MONTH)); // yeah,Calendar sucks
    Assert.assertEquals(21,date.get(Calendar.DAY_OF_MONTH));
}

Solution

Then the input will be divided into three components: year, month and day. You will get month = - 12 and day = - 21 (see correction below) Try to parse 2012 / 12 / 21, you will get an exception:) @ h_ 419_ 4 @ editor: excerpt from Javadoc:

year = "2012"
month = "-1"
day = "2-"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>