Parsing a String into Date with DateFormat not parsing correctly

六月ゝ 毕业季﹏ 提交于 2019-12-17 21:15:41

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/4167485/parsing-a-string-into-date-with-dateformat-not-parsing-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!