views:

302

answers:

3

Hi Folks,

I storing the date to SQLite database in the format

d-MMM-yyyy,HH:mm:ss aaa

And again retrieving it with the same format, the problem now is, I am gettin every thing fine exepth the Hour. Hour I am geting 00 every time, Here the print statement

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);

Please where I am doing wrong.

Cheers, Vinayak

A: 

You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).

Guillaume
I specified the timezone in the format as letter z, problem still persists
Vinayak.B
Your date string doesn't have time zone info so the z letter won't help, use setTimeZone(...) on the SimpleDateFormat object instead
Guillaume
A: 

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!

azp74
Not related but DateFormat objects are not thread safe, they should not be declared static because it makes it more likely that they will be accessed from different threads at some point.
Guillaume
azp74
+2  A: 

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". What does the above code print on your system? If it works, can you reduce your example to a working one that shows the problem?

Thomas Lötzer