SimpleDateFormatter does not recognize months

I want to parse a date string, but I fail. To illustrate my problem, I wrote this simple JUnit test:

@Test
public void testParseJavaDate() throws ParseException {     
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD_HH-mm-ss", Locale.GERMAN);

    String inputtime = "2011-04-21_16-01-08";
    Date parse = sdf.parse(inputtime);

    assertEquals(inputtime,sdf.format(parse));
}

This test failed with this message:

org.junit.ComparisonFailure: Expected result: <2011-0 [4] -21_16-01-08> but was: <2011-0 [1] -21_16-01-08>

I do not understand why the formatter cannot parse the date correctly. Do you have any ideas?

+5
source share
4 answers

You want "dd" (day in the month), not "DD" (day in year):

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.GERMAN);
+6
source

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd_HH-mm-ss", Locale.GERMAN);

String inputtime = "2011-04-21_16-01-08";
Date parse = sdf.parse(inputtime);

use dd instead of DD.

+8

Use dinstead d, because dit is Day after Year, so the month is forced to correspond to the 21st day of the year (which is in January).

+3
source

everything previous is correct, but u should also use 'mm' instead of 'MM' and vice versa because "M" Shows a minute with a zero zero value

therefore ur code will be as follows:

public void testParseJavaDate() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd_HH-MM-ss", Locale.GERMAN);

    String inputtime = "2011-04-21_16-01-08";
    Date parse = sdf.parse(inputtime);

    sdf = new SimpleDateFormat("dd/mm/yyyy HH:MM:ss", Locale.GERMAN);

    System.out.println(sdf.format(parse));

    assertEquals(inputtime, sdf.format(parse));
}

and he will print

run: 21/04/2011 16:01:08 BUILD SUCCESSFUL (total time: 0 seconds)

0
source

All Articles