DateFormat.parse( String s ) != DateFormat.format( Date d )

Hi,

I want to parse a string, using a particular DateFormat, into a Date. I then try to format this date into a String. But this simple reverse function produces different results.

Here is my code:

publicstaticvoid main(String[] args)

{

try

{

ISO8601DateFormat df =new ISO8601DateFormat();

String s1 ="1981-04-06T13:52:30.441GMT";

Date creationDate = df.parse( s1 );

String s2 = df.format( creationDate );

System.out.println("s1: " + s1 );

System.out.println("s2: " + s2 );

}catch( ParseException e )

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

which produces the following results:

s1: 1981-04-06T13:52:30.441GMT

s2: 1981-04-06T14:52:30.441IST

Any ideas why this is?

The ISO8601DateFormat class is as follows:

publicclass ISO8601DateFormatextends SimpleDateFormat

{

public ISO8601DateFormat()

{

super("yyyy-MM-dd'T'HH:mm:ss.SSSz" );

}

}

[1815 byte] By [DeeLeea] at [2007-11-26 19:50:05]
# 1
Obviously, the SimpleDateFormat is using a different timezone. You can set it with DateFormat.setTimeZone.
ProggerFromKupfera at 2007-7-9 22:39:11 > top of Java-index,Java Essentials,Java Programming...
# 2
But why doesn't it read in the timezone from the original string.i.e. GMT is in the 'z' position, so the timezone is GMTI don't want to set the timezone, but the resultant string should simply be of the same timezone as the original string
DeeLeea at 2007-7-9 22:39:11 > top of Java-index,Java Essentials,Java Programming...
# 3
I can't imagine that the time zone is stored in the Date; it just depends on the format. That is, the data stored in a Date is independent from the timezone. Thus, you will have to parse the time zone seperately and then adjust your DateFormat.
ProggerFromKupfera at 2007-7-9 22:39:11 > top of Java-index,Java Essentials,Java Programming...
# 4

> But why doesn't it read in the timezone from the

> original string.

It did, when it parsed it into a Date object, to produce the correct offset from epoch which the Date object represents (Date objects don't contain timezones, just an offset from epoch).

> I don't want to set the timezone, but the resultant

> string should simply be of the same timezone as the

> original string

Then don't parse it into a Date and reformat it again.

By the way, they ARE the same times (moment in time), if the difference between those two timezones (GMT and whatever the other one was) is 1 hour (and I bet it is).

warnerjaa at 2007-7-9 22:39:11 > top of Java-index,Java Essentials,Java Programming...
# 5
yeah, you're right. I added the following line to ISO8601DateFormat, and it's working fine:super.setTimeZone( java.util.TimeZone.getTimeZone("GMT") );Thanks a million
DeeLeea at 2007-7-9 22:39:11 > top of Java-index,Java Essentials,Java Programming...