Java SQLDate valueOf()

In this guide, you will learn about the SQLDate valueOf() method in Java programming and how to use it with an example.

1. SQLDate valueOf() Method Overview

Definition:

The valueOf() method of the java.sql.Date class in Java returns a Date object representing the given date string in YYYY-[M]M-[D]D format.

Syntax:

public static Date valueOf(String s)

Parameters:

- s (String): a string representing a date in the format YYYY-[M]M-[D]D.

Key Points:

- The java.sql.Date class is part of the java.sql package, and it represents a date in the SQL DATE data type.

- The valueOf() method is static and is used to obtain an instance of java.sql.Date from a string representing a date.

- The input string should be in the format YYYY-[M]M-[D]D, and if the string is not in the correct format, a java.lang.IllegalArgumentException is thrown.

- The returned Date object will not have time information, as java.sql.Date only represents the date without time.

- It is useful when you need to convert a string date from SQL data to a Date object in Java.

2. SQLDate valueOf() Method Example

import java.sql.Date;

public class SQLDateExample {
    public static void main(String[] args) {
        // Converting a date string to a SQLDate object using valueOf() method
        String dateString = "2023-09-20";
        Date sqlDate = Date.valueOf(dateString);

        // Printing the SQLDate object
        System.out.println("SQLDate: " + sqlDate);

        // Trying to convert an incorrectly formatted date string (throws IllegalArgumentException)
        try {
            String incorrectDateString = "20-09-2023";
            Date incorrectDate = Date.valueOf(incorrectDateString);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

SQLDate: 2023-09-20
Exception: Timestamp format must be yyyy-mm-dd

Explanation:

In this example, we used the valueOf() method to convert a correctly formatted date string to a java.sql.Date the object and print it. We also demonstrated what happens when trying to convert an incorrectly formatted date string, which results in a java.lang.IllegalArgumentException.

Comments