SimpleDateFormat 在解析“YYYY-MM-dd HH:mm"时产生错误的日期时间 [英] SimpleDateFormat producing wrong date time when parsing "YYYY-MM-dd HH:mm"
问题描述
我正在尝试将 String
(YYYY-MM-dd HH:mm
) 解析为 Date
,但是得到的日期比预期的要错误.
I am trying to parse a String
(YYYY-MM-dd HH:mm
) to Date
, however getting wrong date than expected.
代码:
Date newDate = null;
String dateTime = "2013-03-18 08:30";
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm", Locale.ENGLISH);
df.setLenient(false);
try {
newDate = df.parse(dateTime);
} catch (ParseException e) {
throw new InvalidInputException("Invalid date input.");
}
产生:
美国东部标准时间 2012 年 12 月 30 日星期日 08:30:00(错误)
Sun Dec 30 08:30:00 EST 2012 (wrong)
我尝试将 Lenient 设置为关闭,但没有成功.
I tried setting Lenient off but no luck.
更新
感谢 Sudhanshu 的回答,它帮助我解决了 Java 转换问题.当我将上述代码返回的日期输入数据库时,我正确获取了日期,但时间始终为 00:00
.
Thanks Sudhanshu for the answer, it helped me to solve the Java conversion. When I enter the returned date from the above code into the database I am getting the date correctly but the time is always 00:00
.
ps.setDate(3, new java.sql.Date(app.getDate().getTime()));
推荐答案
YYYY 应该是 yyyy-
YYYY should be yyyy-
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
请在此处查看 SimpleDateFormat 的文档
Java 6:http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Java 7:http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Please check the documentation for SimpleDateFormat here
Java 6 : http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Java 7 : http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
这篇关于SimpleDateFormat 在解析“YYYY-MM-dd HH:mm"时产生错误的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!