Loading...

How do you convert java.util.Date to java.sql.Date in Java?

How do you convert java.util.Date to java.sql.Date in Java?

Hey readers, are you familiar with the date class in java? It has two classes java.util.Date and java.sql.Date to store and format the date. In this article, we will learn how you convert java.util.Date to java.sql.Date in java using different methods.

Introduction

Both the packages, java.util and java.sql have a class Date, but they differ in their usage. java.util.Date is a class used to represent dates and times in java. It provides methods for parsing and formatting date values. as well as you can use it to access other related classes such as Calendar, Duration, and TimeZoneInfo. Instead java.sql.Date is required when you need to read or access date-related information in SQL.

Java also provides two interfaces that we can use to access different parts of the Date object. Gregorian Calendar which is used by Calendar objects (and their implementations) to contain information about weekdays etc. At the same time, based on the current time system zone setting LocalDateTime shows a specific moment in time.

Define java.util.Date vs java.sql.Date 

The two classes, java.util.Date and java.sql.Date, are both subclasses of the same class – java.util.Date. You can use the methods defined in one class when working with instances of another type. that means if you have an instance of a java.util.Date and want to create a new instance of a java-sql-date. You can use java.util.Date class when there is a requirement java.sql.Date but vice-versa is not possible else the program throws an error.

Propertyjava.util.Datejava.sql.Date
Packagejava.utiljava.sql
DescriptionA class representing a specific instant in time, with millisecond precision.A subclass of java.util.Date representing a date (year, month, and day) in the calendar, but with no time information.
TimeIncludes time information (hour, minute, second, and millisecond) in addition to the date.Only includes the date (year, month, and day) and no time information.
StorageIt can be stored in a database as a TIMESTAMP or DATETIME data type.It can be stored in a database as a DATE data type.

Instead of creating an object first, you can also just use their getXXX() methods directly. But remember, this will not work if there is no explicitly set value for year or month/day. For example, using the getTime() method will return time duration in milliseconds.

Why Conversion Is Needed?

The reason why you need to convert java.util.Date to java.sql.Date is because they both roam around the same underlying date class.

The difference between them is that a java.sql.Timestamp object will only store data from a specific point in time. whereas a java.util.Date object stores all possible dates up until the current moment (that’s why it’s called “current” instead of “past”). So if you want to get information about when something happened on a certain day or month. then use this method instead of using methods like getTimeAsLong() or getTime().

How to convert java.util.Date to java.sql.Date?

Using standard conversion

//import SQL and Util date package import java.sql.*; import java.util.*; class CheckDate { public static void main(String[] args){ //Both dates and times will be recorded in Util Package. java.util.Date useUtilDatePackage = new java.util.Date(); // In the SQL package date class contains information of the date only. java.sql.Date useSqlDatePackage = new java.sql.Date(useUtilDatePackage.getTime()); //displaying the output of both packages. System.out.println("utilDate Package in java: " + useUtilDatePackage + "\n"); System.out.println("sqlDate Package in java: " + useSqlDatePackage); } }
Code language: Java (java)

Output

utilDate Package in java: Tue Dec 13 05:09:28 GMT 2022 sqlDate Package in java: 2022-12-13
Code language: Java (java)

By using java.sql.Timestamp Instead of java.sql.Date

You can use java.sql.Timestamp in place of java.sql.Date to convert Date objects to and from a timestamp value in your code. This method is supported by all major databases, including Oracle, SQL Server and MySQL through JDBC drivers that support the standard java Date/Time API (java SE 6).

If you have an application that needs to work with dates but doesn’t need full compliance with JDBC 3010 standards or other restrictions that apply when working with JDBC 4010. then this method will make it possible for you to do so without having any changes or incompatibilities between your code base and the database itself!

import java.sql.*; import java.util.*; public class UseJavaSqlTimeStamp { public static void main(String[] args) { java.util.Date newdate = new java.util.Date(); java.sql.Timestamp byusingtimestamp = new java.sql.Timestamp(newdate.getTime()); System.out.println(newdate); System.out.println(byusingtimestamp); } }
Code language: Java (java)

Output

Tue Dec 13 06:11:22 GMT 2022 2022-12-13 06:11:22.423
Code language: Java (java)

Using Classes From java.time Package

The java.time package is a part of the java Standard Edition 8 (java SE 8) and later, and it provides classes for representing dates, times, and durations. It replaces the older java.util.Date and java.util.Calendar classes, which were problematic because of design issues and poor API design.

Here are some examples of using classes from the java.time package:

LocalDate

//code for creating a LocalDate object import java.time.LocalDate; // Creates a LocalDate object representing the current date LocalDate currentDate = LocalDate.now(); // Creates a LocalDate object representing a specific date LocalDate specificDate = LocalDate.of(2020, 2, 29);
Code language: Java (java)
current: 2022-12-19 localdate: 2020-02-29
Code language: Java (java)

LocalTime

//Creating a LocalTime object import java.time.LocalTime; // Creates a LocalTime object representing the current time LocalTime currentTime = LocalTime.now(); // Creates a LocalTime object representing a specific time LocalTime specificTime = LocalTime.of(12, 0, 0);
Code language: Java (java)
current: 08:59:26.889395 //When you run this code current time will be that time for you. localdate: 12:00
Code language: Java (java)

LocalDateTime

// Now creating a LocalDateTime object import java.time.LocalDateTime; // Creates a LocalDateTime object representing the current date and time LocalDateTime currentDateTime = LocalDateTime.now(); // Creates a LocalDateTime object representing a specific date and time LocalDateTime specificDateTime = LocalDateTime.of(2020, 2, 29, 12, 0, 0);
Code language: Java (java)
current: 2022-12-19T09:03:25.272817 localdatetime: 2020-02-29T12:00
Code language: Java (java)

How to convert from java. util.Date?

To convert a java.util.Date object to a java.sql.Date object, you can use the java.sql.Date constructor that takes a long value as an argument.

Here is an example of how you can convert a java.util.Date object to a java.sql.Date object.

Note that the java.sql.Date class represents a date in the format “YYYY-MM-DD”, without a time component, while the java.util.Date class represents a date and time.

About java.time

In java 8 and later, you can also use java.time package to work with dates and times. The java.time.LocalDate class represents a date without a time, while the java.time.LocalDateTime class represents a date and time. To convert a java.time.LocalDate object to a java.sql.Date object, you can use the java.sql.Date.valueOf() method, which takes a java.time.LocalDate object as an argument.

Here is an example of how you can convert a java.time.LocalDate object to a java.sql.Date object using the valueOf() method.

import java.sql.Date; import java.time.LocalDate; public class Main { public static void main(String[] args) { // Create a java.time.LocalDate object LocalDate localDate = LocalDate.now(); // Convert the java.time.LocalDate object to a java.sql.Date object Date sqlDate = Date.valueOf(localDate); System.out.println("localDate: " + localDate); System.out.println("sqlDate: " + sqlDate); } }
Code language: Java (java)

Output

localDate: 2022-12-17 sqlDate: 2022-12-17
Code language: Java (java)

Java Program to convert java. util.Date to java.sql.Date

import java.util.*; import java.sql.*; public class Main { public static void main(String[] args) { // Create a java.util.Date object java.util.Date utilPackageDate = new java.util.Date(); // Convert the java.util.Date object to a java.sql.Date object java.sql.Date sqlPackageDate = new java.sql.Date(utilPackageDate.getTime()); System.out.println("utilDate: " + utilPackageDate + "\n"); System.out.println("sqlDate: " + sqlPackageDate); } }
Code language: Java (java)

Output

utilDate: Fri Dec 17 10:12:14 UTC 2022 sqlDate: 2022-12-17
Code language: Java (java)

Converting java.util.Date to java.sql.Date – Example

import java.util.Date; import java.sql.*; public class Main { public static void main(String[] args) { // Create a java.util.Date object Date utilDate = new java.util.Date(); // Convert the util.Date object to a java.sql.Date object java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println("utilDate: " + utilDate); System.out.println("sqlDate: " + sqlDate); } }
Code language: Java (java)

Output

utilDate: Fri Nov 20 10:34:42 EST 2020 sqlDate: 2020-11-20
Code language: CSS (css)

The java.util.Date class represents a specific instant in time, with millisecond precision. The java.sql.Date class is a thin wrapper around a java.util.Date object, with the added requirement, that it must represent a date (without time).

To convert a java.util.Date object to a java.sql.Date object, you can simply pass the java.util.Date object to the java.sql.Date constructor, like this.

Conclusion

This blog post is meant as a guide for developers who have to make date conversions in their programs. It went over the syntax and output of each method. as well as how to use classes from java.time the package to perform these conversions. If you’re still having trouble, don’t hesitate to comment. We would love to hear from anyone who has any questions about this topic.

FAQ

How to convert java.util.Date to java.sql.Date using java?

You can learn multiple ways for this conversion from this article. As the first method can be standard conversion, the second will be by using java.sql.Timestamp instead of java.sql.Date and the last can be the use of java.Time package.

How does java.util.Date compare to java.sql.Date? 

java Util date is a library of helper classes and functions, mainly designed to help speed up java applications. It has been designed in such a way that it resembles the java.sql date classes as closely as possible. Former is a class used to represent dates and time both in java. Instead, the latter is required to store the date information in SQL.

How to change the date format in SQL Java?

There are different ways to format a date string into SQL using java.

//first way of date formatting class Tempclass { public static void main(String[] args) { long time=System.currentTimeMillis(); java.sql.Date tempsqldate = new java.sql.Date(time); System.out.println(tempsqldate); } }
Code language: Java (java)

Output

2022-12-19
Code language: Java (java)
//second way of date formatting import java.util.Date; import java.util.Calendar; import java.time.Instant; public class Exampleclass{ public static void main(String argvs[]){ Calendar mycalen = Calendar.getInstance(); mycalen.set(Calendar.MONTH, 13); mycalen.set(Calendar.DATE, 12); mycalen.set(Calendar.YEAR, 2022); Date d = mycalen.getTime(); Instant instantdate = d.toInstant(); System.out.println("The earlier mentioned date is: " + d.toString()); System.out.println("\n" + "The new record of date is: " + instantdate); } }
Code language: Java (java)

Output

The earlier mentioned date is: Sun Feb 12 06:40:56 GMT 2023 The new record of date is: 2023-02-12T06:40:56.040Z
Code language: Java (java)

How is the Date stored in the database Java SQL date java Util date Java SQL DateTime Java Util DateTime?

  • java.sql.Date: This class represents a date (year, month, and day) in the SQL format.
  • java.util.Date: This class represents a date and time, that is used to store timestamps in a database.
  • java.sql.Timestamp: This class is similar to java.util.Date , but it includes additional information such as nanoseconds. It stores more precise timestamps.

What is Java SQL timestamp?

The java SQL timestamp is a column in a database that stores a time value in the standard ISO format. That means, it keeps a track of the date and time records.

Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far