Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

java - SimpleDateFormat producing wrong date time when parsing "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.

CODE:

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

Produces:

Sun Dec 30 08:30:00 EST 2012 (wrong)

I tried setting Lenient off but no luck.

Update

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()));
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

YYYY should be yyyy-

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...