String-Date conversion with nanoseconds

Rhadoozooz picture Rhadoozooz · Aug 17, 2012 · Viewed 45.4k times · Source

I've been struggling for a while with this piece of code for an Android app and I can't get the hang of it. I've read and tried every solution I found on stackoverflow and other places, but still no luck.

What I want to do is have a function to convert a string like "17.08.2012 05:35:19:7600000" to a UTC date and a function that takes an UTC date and converts it to a string like that.

String value = "17.08.2012 05:35:19:7600000";
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");
try
{
  Date today = df.parse(value);
  System.out.println("Today = " + df.format(today) + " " + today.toGMTString());
} 
catch (ParseException e)
{
  e.printStackTrace();
}

This results in : Today = 17.08.2012 07:41:59:0000000 17 Aug 2012 04:41:59 GMT which are both wrong.

I tried setting SDF's timezone to UTC, no luck.
Another thing that I noticed: if I do df.setLenient(false);
It gives me : java.text.ParseException: Unparseable date: "17.08.2012 05:35:19:7600000" .

If anyone can provide me with some explanations / sample code, I would be very grateful. Thanks in advance

Answer

Eric picture Eric · Aug 17, 2012

The result you are getting is absolutely right.

Let's analyze this:

17.08.2012 05:35:19:7600000
  • 17: Day of month (17th)
  • 08: Month of year (August)
  • 2012: Year (2012)
  • 05: Hour of day (5am)
  • 35: Minute of hour (:35)
  • 19: Second of minute (:19)
  • 7600000: Milliseconds of second (7,600,000)

Now, the way the VM sees this is that you are declaring the time of day as 5:35:19am, then adding 7,600,000 milliseconds to it. 7,600,000 milliseconds = 7,600 seconds = 2 hours, 6 minutes, 40 seconds. 5:35:19am + 02:06:40 = 7:41:59am (and 0 milliseconds). This is the result you are getting. (It also appears that you are not setting the timezone properly, so the GMT string is 3 hours behind your result.)

If you want to retain the :7600000, to my knowledge this is not possible. As this can be simplified into seconds, the VM will automatically reduce it into the other time increments. The milliseconds (the SSSS) should be for storing values <1000.

I'd suggest you create a new SimpleDateFormat for your output; but remember that the milliseconds will be absorbed into the other times (since they are all stored as a single long in the Date object).