import java.sql.Date;
public class StringToSQLDateExample {
public static void main(String[] args) {
String str = "2015-03-31";
Date date = Date.valueOf(str); //converting string into sql date System.out.println(date);
}
}
Explanation Step by step:
1. import java.sql.Date;
This imports the java.sql.Date class from the java.sql package. The class java.sql.Date is used to represent SQL DATE values, which contain only the year, month, and day but not time.
2. public class StringToSQLDateExample {
The class StringToSQLDateExample is declared. This is the class where the main method is defined-that is, the entry point of the program.
3. String str = “2015-03-31”
- Declares and initializes a String called str with the literal content “2015-03-31”.
- This string is in YYYY-MM-DD format.
- It is a date.
4. Date date = Date.valueOf(str);
- The Date.valueOf() method is used to convert the String to a java.sql.Date.
- The valueOf() method accepts as a parameter an input string, in the format of YYYY-MM-DD. By coincidence, str is in that format.
- It parses the string and returns a java.sql.Date object representing the date 2015-03-31.
5. System.out.println(date);
- It prints the java.sql.Date object.
- The method System.out.println() automatically invokes the toString() method of the java.sql.Date class, that returns the date in the format YYYY-MM-DD.
Output
Running the above program will output:
2015-03-31
Explanation of Output:
It successfully converts the String “2015-03-31” into the java.sql.Date object and then prints that object in the standard YYYY-MM-DD format. There was no time involved, therefore the printout contains only a date.
Important Points:
- java.sql.Date(String): This method is particularly aimed at converting string, formatted like YYYY-MM-DD, to equivalent java.sql.Date.
- java.sql.Date: It represents SQL date (SQL year, SQL month, and SQL day of month) and does not hold data about time that is hour in minute in seconds.