Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat - parsing timestamps with milliseconds

Tags:

java

I have a timestamp string from a service, it has 6 millisecond digits:

String timestamp = "2014-09-30T15:30:00.777777";

I am parsing it like so:

String format = "yyyy-MM-dd'T'HH:mm:ss.SSS";

DateFormat df = new SimpleDateFormat(format, Locale.ENGLISH);
Date date = df.parse(timestamp);

SimpleDateFormat df2 = new SimpleDateFormat();
System.out.println(df2.format(date));

I am expecting to see:

"9/30/14 3:30 PM"

but instead I get:

"9/30/14 3:42 PM"

twelve minutes ahead. I tried using a different format string with 6 ms digits:

String format = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";

Same result.

It seems what I have to do is manually truncate the incoming timestamp strings to 3 ms digits:

timestamp = timestamp.substring(0, timestamp.length()-3);

then I get the expected result. Or I can use a truncated format string that ignores milliseconds:

String format = "yyyy-MM-dd'T'HH:mm:ss";

Are those correct solutions? Am I just misusing SimpleDateFormat?

Thank you

like image 477
user1219278 Avatar asked Dec 25 '22 03:12

user1219278


2 Answers

777777 milliseconds ~ 12 minutes

3:30 PM + 12 minutes = 3:42 PM

Your parser is working correctly.

The real question: Why is your source data giving you 6-digit millisecond values? Is it supposed to be interpreted as 777.777 milliseconds?

like image 80
Cory Klein Avatar answered Jan 14 '23 19:01

Cory Klein


SimpleDateFormat thinks the milliseconds part is 777777 and since it is greater than 1000, the part over 1000 will be rolled, converted to seconds and minutes. Yes, in your case you should truncate the input because it is not milliseconds but microseconds ( and SimpleDateFormat has no symbol for parsing microseconds).

like image 45
icza Avatar answered Jan 14 '23 20:01

icza