java.util.Date to java.sql.Date
In this example, we shall show you how to convert a java.util.Date object to a java.sql.Date object. This conversion is usually necessary when a Date
object needs to be written in a database.
java.util.Date represents a specific instant in time, with millisecond precision. It represents both date and time.
java.sql.Date is a wrapper around millisecond value and is used by JDBC
to identify an SQL DATE
type. It is a subclass of java.util.Date
. Though, it only represents date information, so hours, minutes, seconds, and milliseconds must be set to zero in a specified time zone, so that this date is equivalent to an SQL DATE
type.
In DatesConversion.java
class below, we use the java.util.Date()
constructor, that creates a Date
object and initializes it to represent time to the nearest millisecond. This date
is used in the convertUtilToSql(java.util.Date uDate)
method to return a java.sql.Date
object. In this method, the java.util.Date object is converted to a java.sql.Date object, using the java.sql.Date(long date)
constructor. This constructor needs a long
param, which is the time value in milliseconds. So, the getTime()
API method of java.util.Date is used here that returns the number of milliseconds since January 1, 1970, 00:00:00 GMT of this date object.
So, this is it! The java.util.Date is converted to java.sql.Date.
DatesConversion.java:
package com.javacodegeeks.snippets.core; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * java.util.date to java.sql.date */ public class DatesConversion { public static void main(String[] args) { java.util.Date uDate = new java.util.Date(); System.out.println("Time in java.util.Date is : " + uDate); java.sql.Date sDate = convertUtilToSql(uDate); System.out.println("Time in java.sql.Date is : " + sDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss"); System.out.println("Using a dateFormat date is : " + df.format(uDate)); } private static java.sql.Date convertUtilToSql(java.util.Date uDate) { java.sql.Date sDate = new java.sql.Date(uDate.getTime()); return sDate; } }
Run the example. The result is the one below:
Output:
Time in java.util.Date is : Tue Oct 21 00:21:54 EEST 2014 Time in java.sql.Date is : 2014-10-21 Using a dateFormat date is : 21/10/2014 - 12:21:54
As you can see, java.util.Date
has both date and time information, whereas java.sql.Date
only has date information.
This was an example of how to convert a java.util.Date object to a java.sql.Date object.