日期字符串解析问题(由于月份从0到11)
该代码
String strDate = "2010-12-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date parsedDate = sdf.parse(strDate);
System.out.println(parsedDate);
将根据您的语言环境产生以下输出:
Fri Jan 01 00:12:00 CET 2010
日期未正确解析,因为我期望是 12 月 1 日,而不是 1 月 1 日。 我知道,月份是从 0 到 11 编号的,所以 12 就变成了 1 月的 0。
对于这个问题,我有几种解决方案,但它们都将产生至少 3-4 行额外的代码。所以我的问题是:
解决这个“问题”的最好方法是什么?
我无法想象解析一个简单的日期需要超过 2-3 行...
//编辑:我为这个问题感到羞耻。对不起。谢谢大家
The code
String strDate = "2010-12-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date parsedDate = sdf.parse(strDate);
System.out.println(parsedDate);
will, dependend on your locale, produce the following output:
Fri Jan 01 00:12:00 CET 2010
The date is not parsed correctly, since i expect the 1st dec and not the 1st jan.
I know, months are numbered from 0 to 11, so the 12 becomes a 0 for january.
I have several solutions for this problem in mind, but all of them will produce at least 3-4 additional lines of code. So my question is:
What is the nicest way to solve this "problem"?
I can't imagine that it takes more than 2-3 lines to parse a simple date...
//edit: Shame on me for this question. Forgive me. thx folks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
yyyy-mm-dd
更改为yyyy-MM-dd
参见
SimpleDateFormat
change
yyyy-mm-dd
toyyyy-MM-dd
See
SimpleDateFormat
您的日期格式不正确:月份是
MM
(不是mm
,它表示分钟)。试试这个:你得到一月的原因是你没有给解析器一个月(你给了年-分-日)。如果输入未提供,一月(第一个月)是分配给该日期的默认月份。
12
被解析为分钟字段(相当明显)Your date format is incorrect: Months are
MM
(notmm
, which is for minutes). Try this:The reason you are getting January is that you haven't given a month to the parser (you gave year-minute-day). January, the first month, is the default month allocated to the date if not provided by the input. The
12
got parsed into the minute field (fairly obviously)使用不同的类。您正在使用麻烦的旧遗留类。而是使用 java.time 类。
LocalDate
LocalDate
类表示仅日期值,没有时间和时区。它可以合理地计算月份,1-12 是一月到十二月。您的输入字符串已采用 ISO 8601 格式之一。 java.time 类中默认使用这些标准格式。因此不需要定义格式化模式。
月份
另请查看方便的
Month
枚举。Use different classes. You are using troublesome old legacy classes. Instead use the java.time classes.
LocalDate
The
LocalDate
class represents a date-only value without time-of-day and without time zone. It counts months sensibly, 1-12 is January through December.Your input string is already in one of the ISO 8601 formats. These standard formats are used by default in the java.time classes. So no need with defining a formatting pattern.
Month
Also check out the handy
Month
enum.