Java Timestamp valueOf()

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

1. Timestamp valueOf() Method Overview

Definition:

The valueOf() method of the Timestamp class in Java is a static method used to convert a string representing a timestamp in the format "yyyy-[m]m-[d]d hh:mm:ss[.f...]" to a Timestamp object.

Syntax:

public static Timestamp valueOf(String s)

Parameters:

- s: A string representing a timestamp in the format "yyyy-[m]m-[d]d hh:mm:ss[.f...]".

Key Points:

- The Timestamp class is part of the java.sql package.

- The valueOf() method throws IllegalArgumentException if the given string does not follow the correct format.

- The method is particularly useful when there is a need to convert a string representation of a timestamp back to a Timestamp object, such as when reading from a database or a file.

- The fractional seconds are optional; if present, they must be separated from the seconds by a decimal point and can be 1-9 digits long.

2. Timestamp valueOf() Method Example

import java.sql.Timestamp;

public class TimestampExample {
    public static void main(String[] args) {
        // A valid string representing a timestamp
        String timestampStr = "2023-09-20 12:45:30.123456789";

        // Converting the string to a Timestamp object
        Timestamp timestamp = Timestamp.valueOf(timestampStr);

        // Printing the Timestamp object
        System.out.println("Timestamp from String: " + timestamp);

        // Attempting to create a Timestamp from an invalid string
        try {
            Timestamp invalidTimestamp = Timestamp.valueOf("invalid-timestamp-string");
            System.out.println("Invalid Timestamp: " + invalidTimestamp);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Timestamp from String: 2023-09-20 12:45:30.123456789
Exception: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

Explanation:

In this example, we successfully created a Timestamp object from a valid string representing a timestamp and printed it. We also attempted to create a Timestamp from an invalid string, which resulted in an IllegalArgumentException, demonstrating that the input string must conform to the timestamp format.

Comments