How to Convert String to Java.sql.Date


In this example, we will write an example to convert String object containing date to java.sql.Date object in Java.

Source Code

package com.beginner.examples;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ConvertStringToJavaSQLDate {

	public static void main(String[] args) throws ParseException {
		
		//String date.
		String strDate = "2019-01-21 00:00:00";
		
		/*
		 * To convert String to java.sql.Date, use
		 * Date (long date) constructor.
		 */
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

		java.util.Date date = sdf.parse(strDate);
		
		java.sql.Date sqlDate = new Date(date.getTime());
		
		System.out.println("String converted to java.sql.Date :" + sqlDate);

	}

}

Output:

String converted to java.sql.Date :2019-01-21

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments