Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()));
like image 560
Sas Avatar asked Apr 10 '13 04:04

Sas


People also ask

How parse DD MMM YYYY in Java?

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.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.


3 Answers

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

like image 94
Sudhanshu Umalkar Avatar answered Oct 06 '22 01:10

Sudhanshu Umalkar


Use small case Y, not caps. ie yyyy not YYYY

Check the comments here: Java Simple Date Format and other answers referenced there.

like image 41
RaymondMachira Avatar answered Oct 06 '22 00:10

RaymondMachira


There are two problem.

  1. Format string should be "yyyy-MM-dd HH:mm".
  2. Datatype to store the time is TimeStamp and not Date in database.

Correct both the things and you will be able to store and retrieve Date with time.

like image 41
Rais Alam Avatar answered Oct 06 '22 00:10

Rais Alam