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 ever
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!
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".
While in 2010, java.util.Date
was the class we all used (toghether with DateFormat
and Calendar
), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss");
String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter);
System.out.println("output here: " + dateTime);
Output is:
output here: 2010-04-29T13:00:14
The combination of uppercase HH
and aaa
in your format pattern strings does not make much sense since HH
is for hour of day, rendering the AM/PM marker from aaa
superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat
or the modern DateTimeFormatter
:
'aaa' should not be used, if you use 'aaa' then specify 'hh'
Lowercase hh
is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.
Other tips
2010-04-29T07:30:14Z
(the modern Instant
class parses and formats such strings as its default, that is, without any explicit formatter).GMT+05:30
for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.DateFormat
, its parse
method returns a Date
, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);
.Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).