Convert String to java.util.Date
I am storing the dates in a SQLite database in this format:
d-MMM-yyyy,HH:mm:ss aaa
When I retrieve the date with that format I am get every thing fine
except the hour. The hour is always 00
. Here is my output:
String date--->29-Apr-2010,13:00:14 PM
After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010
Here is the code:
Date lScheduledDate = CalendarObj.getTime();
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
SomeClassObj.setTime(formatter.format(lScheduledDate));
String lNextDate = SomeClassObj.getTime();
DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date lNextDate = (Date)lFormatter.parse(lNextDate);
System.out.println("output here"+lNextDate);
What am I doing wrong?
Solution 1:
I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.
Nevertheless, this works fine for me:
String testDate = "29-Apr-2010,13:00:14 PM";
DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
Date date = formatter.parse(testDate);
System.out.println(date);
It prints "Thu Apr 29 13:00:14 CEST 2010".
Solution 2:
It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
You declare your date format and then call the parse method with your string.
private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");
And as Guillaume says, set the timezone!