Java SQLTime valueOf()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

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

1. SQLTime valueOf() Method Overview

Definition:

The valueOf() method of the java.sql.Time class in Java returns a Time object representing the given time string in hh:mm:ss format.

Syntax:

public static Time valueOf(String s)

Parameters:

- s (String): a string representing time in the format hh:mm:ss.

Key Points:

- The java.sql.Time class is part of the java.sql package, and it represents a time in the SQL TIME data type.

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

- The input string should be in the format hh:mm:ss, and if the string is not in the correct format, a java.lang.IllegalArgumentException is thrown.

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

- This method is useful when you need to convert a string time from SQL data to a Time object in Java.

2. SQLTime valueOf() Method Example

import java.sql.Time;

public class SQLTimeExample {
    public static void main(String[] args) {
        // Converting a time string to a SQLTime object using valueOf() method
        String timeString = "14:05:30";
        Time sqlTime = Time.valueOf(timeString);

        // Printing the SQLTime object
        System.out.println("SQLTime: " + sqlTime);

        // Trying to convert an incorrectly formatted time string (throws IllegalArgumentException)
        try {
            String incorrectTimeString = "14:05";
            Time incorrectTime = Time.valueOf(incorrectTimeString);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

SQLTime: 14:05:30
Exception: java.lang.IllegalArgumentException

Explanation:

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

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare