We are using SimpleDateFormat in JAXB serialization/deserialization process of java.util.Date objects and I'm writing following utility to accomplish that
public DateFormat getDateFormat(String format){
DateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
return formatter;
}
@Test public void testMarshallUnmarshall(){
String str1 = "2001-07-04T12:08:56.235-07:00"; // Example from http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html DateFormat formatter = getDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = formatter.parse(str1);
String str2 = formatter.format(date);
assertEquals(str1.equals(str2)); //This fails }
What I noticed is str1 = "2001-07-04T12:08:56.235-07:00"; and str2 = 2001-07-04T14:08:56.235-05:00
What I need to do to make sure, both dates are same?
Thanks
The two strings represent the same instant in time - it's just that one has a different UTC offset than the other.
That's to be expected - a Date
only represents a point in time, and it looks like you've set up your SimpleDateFormat
using the default system time zone. Therefore, any time you parse a value which has an offset other than the one that point in time would have in the system default time zone, you won't be able to round-trip the string.
If you compare the Date
values, you'll find they are equal - in other words, if you compare formatter.parse(str2)
with date
, that should be fine.
Alternatively, use a format which is always in UTC, instead of one which specifies the time zone offset... or use a different data type which can preserve the offset.
See more on this question at Stackoverflow