Question

I've been searching all over and just can't find a explanation or reason why this is happening but the parse(String) method of DateFormat just isn't parsing my String correctly.

I'm trying to parse a String into the date format that is used for HTTP headers and got as far as getting the String on its own such as:

Thu, 11 Nov 2010 18:34:22 GMT

Which is in the format:

E, d MMM yyyy HH:mm:ss z

But when I use df.parse(dateStr); this is what I get out of it:

Thu Nov 11 18:34:22 GMT 2010

Which is nothing like what I wanted, why is the year now after the GMT? Why is there no comma anymore? And why is the date after the month?

I'm completely confused about this now and can't find a solution but I really need the date to be in that format. Is the comma messing things up? or the colons?

Thanks for your time,

Infinitifizz

P.S.

Forgot to mention this but I've tried dateformat.setLenient(false) and it makes no difference.

P.P.S

I'm trying to do this to compare the dates with date1.before(date2) and after() etc to see if one is newer than the other but I can't do this because the parsing isn't working.

Even though they look the same but just the format is different, they are not the same because after calling getTime() on both of them (When I have provided 2 identical dates) the longs are not the same. As in the date is:

Thu, 11 Nov 2010 19:38:52 GMT for a lastModified() on a File

If I input the String "Thu, 11 Nov 2010 19:38:52 GMT" and then compare their longs once converting the string to a date using parse() and then calling getTime() on that date I get:

lastModified = 1289504332671 fromString = 1289504332000

It is only the last 3 digits that are different, does this have any significance?

Thanks again for your time and sorry I didn't put this bit in first,

Infinitifizz

Was it helpful?

Solution

The result format is the default format of Date#toString() (click link to see the javadoc). You're apparently doing a System.out.println(date). You would like to use SimpleDateFormat#format() instead with another pattern to format it in the desired format. E.g.

String newDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

Update: You shouldn't care about the format when using Date. You should only care about the format at that point when Date is to be converted (displayed) as String. As to the difference in timestamps, the Date uses millisecond precision for the timestamp while HTTP header uses second precision. You'd like to divide the timestamps by 1000 before comparing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top