解析“YYYY-MM-dd HH:mm”时,SimpleDateFormat产生错误的日​​期时间。 [英] SimpleDateFormat producing wrong date time when parsing "YYYY-MM-dd HH:mm"

查看:159
本文介绍了解析“YYYY-MM-dd HH:mm”时,SimpleDateFormat产生错误的日​​期时间。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串 YYYY-MM-dd HH:mm )解析为日期,但错误的日期超出预期。

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.");
}

产生:


Sun Dec 30 08:30:00 EST 2012(错误)

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

这篇关于解析“YYYY-MM-dd HH:mm”时,SimpleDateFormat产生错误的日​​期时间。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆