Parameter | Explanation |
---|---|
No parameter | Creates a new Date object using the allocation time (to the nearest millisecond) |
long date | Creates a new Date object with the time set to the number of milliseconds since "the epoch" (January 1, 1970, 00:00:00 GMT |
java.util.Date to java.sql.Date conversion is usually necessary when a Date object needs to be written in a database.
java.sql.Date is a wrapper around millisecond value and is used by JDBC to identify an SQL DATE type
In the below example, 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 convert(java.util.Date utilDate) method to return a java.sql.Date object
Example
public class UtilToSqlConversion { public static void main(String args[]) { java.util.Date utilDate = new java.util.Date(); System.out.println("java.util.Date is : " + utilDate); java.sql.Date sqlDate = convert(utilDate); System.out.println("java.sql.Date is : " + sqlDate); DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss"); System.out.println("dateFormated date is : " + df.format(utilDate)); } private static java.sql.Date convert(java.util.Date uDate) { java.sql.Date sDate = new java.sql.Date(uDate.getTime()); return sDate; } }
Result:
java.util.Date is : Fri Dec 29 17:23:15 UTC 2023 java.sql.Date is : 2023-12-29 dateFormated date is : 29/12/2023 - 05:23:15
java.util.Date has both date and time information, whereas java.sql.Date only has date information
Using the following code with the format string yyyy/MM/dd hh:mm.ss, we will receive the following output
2023/12/29 10:45.59
// define the format to use String formatString = "yyyy/MM/dd hh:mm.ss"; // get a current date object Date date = Calendar.getInstance().getTime(); // create the formatter SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatString); // format the date String formattedDate = simpleDateFormat.format(date); // print it System.out.println(formattedDate); // single-line version of all above code System.out.println(new SimpleDateFormat("yyyy/MM/dd hh:mm.ss").format(Calendar.getInstance().getTime()));
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions