Please find the following codes:
@RunWith(JUnit4.class)
public class TestTimestamp {
private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss.SSSSSS");
private final static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
@Test
public void test() throws ParseException {
getTimestamp("20140512 16:13:09.493166 +0800", sdf);
getTimestamp("20140515 15:04:42.690873 +0800", sdf);
getTimestamp("20140515 15:04:45.159977 +0800", sdf);
getTimestamp("20140512 16:13:09.493166 +0800", df);
getTimestamp("20140515 15:04:42.690873 +0800", df);
getTimestamp("20140515 15:04:45.159977 +0800", df);
}
private void getTimestamp(String time, SimpleDateFormat sdf) throws ParseException {
System.out.println("Time to convert: " + time);
String[] tmp = time.split("\\+");
String str = tmp[0].trim();
System.out.println(str);
System.out.println(sdf.parse(str));
System.out.println();
}
}
The output with sdf
is very strange and the output with df
is correct:
//Wrong result with sdf
Time to convert: 20140512 16:13:09.493166 +0800
20140512 16:13:09.493166
Mon May 12 16:21:22 CST 2014
Time to convert: 20140515 15:04:42.690873 +0800
20140515 15:04:42.690873
Thu May 15 15:16:12 CST 2014
Time to convert: 20140515 15:04:45.159977 +0800
20140515 15:04:45.159977
Thu May 15 15:07:24 CST 2014
//Correct result with df
Time to convert: 20140512 16:13:09.493166 +0800
20140512 16:13:09.493166
Mon May 12 16:13:09 CST 2014
Time to convert: 20140515 15:04:42.690873 +0800
20140515 15:04:42.690873
Thu May 15 15:04:42 CST 2014
Time to convert: 20140515 15:04:45.159977 +0800
20140515 15:04:45.159977
Thu May 15 15:04:45 CST 2014
Could you please help me out?
a millisecond would be SSS being a thousandth. The 159977 length would exceed this being a microsecond
try
yyyyMMdd HH:mm:ss.SSS