I want to parse a date string but I fail miserably. 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 fails with this message:
org.junit.Com开发者_运维问答parisonFailure: expected:<2011-0[4]-21_16-01-08> but was:<2011-0[1]-21_16-01-08>
I don't get why the formatter cannot parse the date correctly. Do you have any ideas?
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.
You want "dd" (day in month), not "DD" (day in year):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.GERMAN);
Use d
instead of D
, as D
is the 'Day in year', so the month is forced to match the 21st day of the year (which is in January).
all the previous is right but u must also use 'mm' in place of 'MM' and vise versa because 'M' Display minute with a leading zero as necessary
so 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 it will print
run:
21/04/2011 16:01:08
BUILD SUCCESSFUL (total time: 0 seconds)
精彩评论