Date object SimpleDateFormat not parsing timestamp string correctly in Java (Android) environment

Try removing the fractional seconds from the format string. I just ran into the same issue, but with a slightly different format. My input format wasn’t in ISO format (no “T”, and no “Z”), but the symptom was the same — time was off by some random number of minutes and seconds, but everything else was fine. This is what my log results looked like:

When using the fractional second format:

SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");

# Parsed date: 2011-05-27 17:11:15.271816 => Fri May 27 17:15:46 EDT 2011
# Parsed date: 2011-05-27 17:09:37.750343 => Fri May 27 17:22:07 EDT 2011
# Parsed date: 2011-05-27 17:05:55.182921 => Fri May 27 17:08:57 EDT 2011
# Parsed date: 2011-05-27 16:55:05.69092 => Fri May 27 16:56:14 EDT 2011
# Parsed date: 2011-05-27 16:38:35.50348 => Fri May 27 16:39:25 EDT 2011

I fixed it by removing the fractional seconds from the format.

SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

# Parsed date: 2011-05-27 17:11:15.271816 => Fri May 27 17:11:15 EDT 2011
# Parsed date: 2011-05-27 17:09:37.750343 => Fri May 27 17:09:37 EDT 2011
# Parsed date: 2011-05-27 17:05:55.182921 => Fri May 27 17:05:55 EDT 2011
# Parsed date: 2011-05-27 16:55:05.69092 => Fri May 27 16:55:05 EDT 2011
# Parsed date: 2011-05-27 16:38:35.50348 => Fri May 27 16:38:35 EDT 2011

What I think is happening is that my “fractional seconds” part of the input string is too long (the same is true in the OP example). It appears to be expecting only three decimal places. If you do the math (take the first example):

  • fractional seconds = 0.271816 seconds
  • What DateFormat sees is 271816 / 1000 of a second
  • 271816 / 1000 == 271 seconds
  • 271 / 60 = 4 minutes
  • 271 % 60 = 31 seconds
  • 17:11:15 to 17:15:46 is exactly 4 minutes, 31 seconds off

Leave a Comment