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()));
How to parse a date? String input = "Thu Jun 18 20:56:02 EDT 2009"; SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); Date date = parser. parse(input); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatter.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
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
Use small case Y, not caps. ie yyyy not YYYY
Check the comments here: Java Simple Date Format and other answers referenced there.
There are two problem.
"yyyy-MM-dd HH:mm"
.TimeStamp
and not Date
in database.Correct both the things and you will be able to store and retrieve Date with time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With