使用SimpleDateFormat不一致的日期解析 [英] Inconsistent date parsing using SimpleDateFormat
问题描述
SimpleDateFormat
,没有任何麻烦,但现在,使用SimpleDateFormat来解析日期是(仅有时)只是一个简单的错误。 具体来说:
SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd hh: mm:ss);
日期date = sdf.parse(2009-08-19 12:00:00);
System.out.print(date.toString());
打印字符串 Wed Aug 19 00:00:00 EDT 2009
。有没有搞错? - 它甚至不会一直解析到错误的日期!
更新:这固定好了。你不会知道的,那也是在其他几个地方被滥用了。想要调试别人的代码:)
我想你想使用 HH
格式,而不是'hh',以便您在00-23之间使用时间。 'hh'采用12小时递增的格式,因此它假定它在AM中。
所以这个
SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
日期date = sdf.parse(2009-08-19 12:00:00);
System.out.print(date.toString());
应打印出
Wed Aug 19 12:00:00 EDT 2009
I'm really scratching my head on this one. I've been using SimpleDateFormat
s with no troubles for a while, but now, using a SimpleDateFormat to parse dates is (only sometimes) just plain wrong.
Specifically:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());
prints the string Wed Aug 19 00:00:00 EDT 2009
. What the heck? - it doesn't even parse into the wrong date all the time!
Update: That fixed it beautifully. Wouldn't you know it, that was misused in a few other places as well. Gotta love debugging other people's code :)
I think you want to use the HH
format, rather than 'hh' so that you are using hours between 00-23. 'hh' takes the format in 12 hour increments, and so it assumes it is in the AM.
So this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2009-08-19 12:00:00");
System.out.print(date.toString());
Should print out
Wed Aug 19 12:00:00 EDT 2009
这篇关于使用SimpleDateFormat不一致的日期解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!