Java SimpleDateFormat解析错误的日期 [英] Java SimpleDateFormat Parse Wrong Date
问题描述
我正在尝试使用 SimpleDateFormat
的解析函数将 String
转换为日期
I'm trying to use the parse function of SimpleDateFormat
to turn a String
into a Date
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY");
String strInput1 = "29-04-2014";
System.out.println("string 1: " + strInput1);
Date date1 = new Date();
try {
date1 = sdf.parse(strInput1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 1: " + date1.toString());
String strInput2 = sdf.format(date1);
System.out.println("string 2: " +strInput2);
Date date2 = new Date();
try {
date2 = sdf.parse(strInput2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("date 2 " + date2);
date1
的输出是 Mon Dec 30 00:00:00 GMT 2013
,然后正确解析为 30-12-2014
。
The output for date1
is Mon Dec 30 00:00:00 GMT 2013
, which is then correctly parsed to 30-12-2014
.
我认为当初始化 sdf
时,错误就在某处。
I assume the mistake is somewhere when sdf
is initialized.
推荐答案
您正在使用 YYYY
这是周年。你的意思是 yyyy
,这是年。
You're using YYYY
which is the week year. You mean yyyy
, which is the year.
只需将格式更改为:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
很少使用 YYYY
格式说明符,当 使用时,它应与 E
/ u
一起使用(星期几的名称/号码)和 w
(星期几)。
The YYYY
format specifier is rarely used, and when it is used, it should be used in conjunction with E
/u
(day of week name/number) and w
(week of week year).
请注意,您应该考虑设置你的 SimpleDateFormat
的时区......另外,如果你使用的是Java 8,请使用 java.time
包,以及 Joda Time 是一个比 java.util更清晰的库。日期
等。
Note that you should consider setting the time zone of your SimpleDateFormat
as well... additionally, if you're using Java 8, use the java.time
package, and otherwise Joda Time is a much cleaner library than java.util.Date
etc.
这篇关于Java SimpleDateFormat解析错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!