Search code examples
javadate-formatsimpledateformatdatetime-format

Why is string to date and back to string resulting in two different strings?


My input string is:

"2016-06-13T14:20:09.866Z"

My output string is:

"2016-06-13T10:20:09.866-04"

Why are they different and how can I make it output in the same format as the input?

I convert from string to date:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.parse((String) date));

In a unit test, I convert the parsed date back into a string:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.format(date);

Solution

  • The two dates are the same - only the format differs (one is 2pm UTC the other is 10am with an offset of -4 hours = 2pm UTC too).

    So I suppose that what you want is to have the second string in UTC time zone too. In that case you can simply set the timezone of the second DateFormat:

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));