[java] 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?

This question is related to java date datetime-format

The answer is


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!


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


java.time

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

What went wrong in your code?

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

  • In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
  • Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
  • If you wanted to use the outdated DateFormat, its parse method returns a Date, so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate);.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime-format

How do I convert 2018-04-10T04:00:00.000Z string to DateTime? Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How can I create basic timestamps or dates? (Python 3.4) Format Instant to String Laravel $q->where() between dates How to Convert datetime value to yyyymmddhhmmss in SQL server? AngularJS - convert dates in controller Display DateTime value in dd/mm/yyyy format in Asp.NET MVC Display date in dd/mm/yyyy format in vb.net Convert DataFrame column type from string to datetime, dd/mm/yyyy format