I am having problem parsing dates in Java. Below is the code.
String dateString = "2017-12-13T16:49:20.730555904Z";
List<String> formatStrings = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'");
for (String formatString : formatStrings)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat(formatString);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = formatter.parse(dateString);
System.out.println("Format is:" + formatString);
System.out.println("Orignal Date: " + d);
System.out.println("Orignal MS: " + d.getTime());
return d;
}
catch (ParseException e) {}
}
return null;
}
When I run this program, I get the following output.
Format is:yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'
Orignal Date: Fri Dec 22 03:45:15 UTC 2017
Orignal MS: 1513914315904
I am not sure why it is giving me Dec 22 when it should be Dec 13. But if I change my input date to this.
String dateString = "2017-12-13T16:49:20.7Z";
i.e only one character before the Z. then I get the correct output.
Format is:yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'
Orignal Date: Wed Dec 13 16:49:20 UTC 2017
Orignal MS: 1513183760007
It gives me correct output till 3 numbers before the Z. If more than 3 numbers than I got the wrong output.
It would be great if someone can point me out what I am missing here.
PS: I am parsing these dates in android. I have set min API level to 16 and java.time is not available for API level below 26.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…