2

In my application, I'm reading a String value from a file which represents a time in UTC format and is generated by .net 2015. In my application which is in Java, I read this value and need to convert it into a long value first and then convert it back to a UTC time. Here is my code in Java to convert time to long value:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(timeString);
long timeLong = date.getTime();

and to convert it back to UTC format:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date(timeLong);               
newTimeStamp = df.format(date);

However, the final UTC time I get is not the same as the original time I read from file. It has almost two hours difference. I want to know whether it is because of the difference in implementation of time conversion in Java and .Net.

My original time is 2015-12-22T21:00:11.8701036Z and the final time I get after doing this conversion is 2015-12-22T23:25:12.000036Z.

p.s. I'm using Java 1.7.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
HHH
  • 6,085
  • 20
  • 92
  • 164
  • Possible duplicate of [SimpleDateFormat parse loses timezone](http://stackoverflow.com/questions/18122608/simpledateformat-parse-loses-timezone) – childofsoong Dec 23 '15 at 17:51
  • I flagged you for a duplicate of http://stackoverflow.com/questions/18122608/simpledateformat-parse-loses-timezone - I found that after realizing that when I did your code, I was off by 8 hours (the number of hours I'm off from UTC). I presume you're at UTC +/- 2? – childofsoong Dec 23 '15 at 17:52
  • One of the major deficiencies with the `Date` class is that it isn't intrinsically time-zone aware unless you create it from a `Calendar` instance. This is part of the reason why Java 8 has a new Date API, including the `ZonedDateTime` class. – Powerlord Dec 23 '15 at 17:55
  • I think you didn't have a duplicate after all - I'm writing an answer explaining – childofsoong Dec 23 '15 at 17:58
  • @soong: do you have a solution for it? – HHH Dec 23 '15 at 18:33
  • @H.Z. No. After realizing that the `Z` was a literal, I reviewed my code, and realized I was looking at my output wrong (I'm using a scala REPL, and I looked at how it interpreted my DateTime object in my time zone, rather than the original string). I think Sotirios's answer is correct. – childofsoong Dec 23 '15 at 18:35

1 Answers1

2

The S pattern in SimpleDateFormat represents milliseconds, not fractional milliseconds. As such, 8701036 is parsed as 8701036 milliseconds, which adds 8701 seconds to the total date (or timestamp). That is equivalent to the additional 2 hours, 25 minutes, and 1 second you're seeing.

SimpleDateFormat doesn't work with fractions of milliseconds. You'll have to parse them out yourself as far as I know.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724