Bala
Bala

Reputation: 61

ISO 8601 date format string to Date object in Java

I tried searching answer for different formats of ISO 8601 date only but not able to identify answer or material which contains these details

I am trying to receive ISO 8601 date format(date only as its date of birth) string and convert it into date object and later persist in dB. Is yyyy-MM-dd only date format that is considered as ISO 8601 date format. If so I can handle this accordingly but is there multiple date ISO 8601 date formats, if so can you please guide what is the best way to parse given string and convert to date object in Java

Upvotes: 0

Views: 1669

Answers (1)

Anonymous
Anonymous

Reputation: 86232

Yes, yyyy-MM-dd is the ISO 8601 format for a date without time of day and without time zone.

To store into an SQL database using either a JDBC 4.2 or later driver or a modern JPA implementation such as Hibernate 5, you have got nothing to use a Date object for (no matter if you meant java.util.Date or java.sql.Date). I recommend that instead you use java.time, the modern Java date and time API. The class to use for a date without time of day is LocalDate. And you can store one into your database without any conversion.

LocalDate parses ISO 8601 format as its default, that is, without any explicit formatter:

    String receivedString = "1962-11-27";
    LocalDate dateOfBirth = LocalDate.parse(receivedString);
    System.out.println("Date of birth is " + dateOfBirth);

LocalDate also gives ISO 8601 format back when we print it:

Date of birth is 1962-11-27

I haven’t given you the full story yet, though. yyyy-MM-dd is the extended format that is by far most often used. There is also a basic format that is compacter in that it leaves out the hyphens: yyyyMMdd. I suggest that you insist on getting your date string in the extended format. If you cannot do that, you will have to specify a formatter for parsing:

    String receivedString = "19621127";
    LocalDate dateOfBirth = LocalDate.parse(
            receivedString, DateTimeFormatter.BASIC_ISO_DATE);

This will give you a LocalDate equal to and indistinguishable from the one we had before.

To save into your database using JDBC:

    PreparedStatement pStmt
            = yourDatabaseConnection.prepareStatement(
                    "insert into your_table (date_of_birth) values (?);");
    pStmt.setObject(1, dateOfBirth);
    int insertedRows = pStmt.executeUpdate();

Note the use of setObject(), not setDate().

Links

Upvotes: 2

Related Questions