Home > Java > javaTutorial > How to Convert a Java `java.util.Date` to a `java.sql.Date`?

How to Convert a Java `java.util.Date` to a `java.sql.Date`?

Susan Sarandon
Release: 2025-01-05 04:30:40
Original
625 people have browsed it

How to Convert a Java `java.util.Date` to a `java.sql.Date`?

Converting Java Date to SQL Date: A Comprehensive Guide

When working with Java, there are times when you may encounter the need to convert a java.util.Date object into a java.sql.Date object. While these classes share similar functionality, they have underlying differences that necessitate an explicit conversion process.

The Problem

Initially, the conversion might seem straightforward, but Java does not implicitly or explicitly support direct conversion between these two data types.

The Solution

Fortunately, the solution is simple and involves using the java.sql.Date constructor, which takes a long value representing milliseconds since the epoch. Here's a step-by-step guide:

  1. Retrieve the milliseconds since the epoch from the java.util.Date object using the getTime() method.
  2. Create a new java.sql.Date object by passing the milliseconds to its constructor.
  3. Assign the created java.sql.Date object to your desired variable.

Sample Code

The following code snippet demonstrates the conversion process:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
Copy after login

Conclusion

By following these steps, you can easily convert a java.util.Date object into a java.sql.Date object, allowing you to use the latter in contexts where it is explicitly required.

The above is the detailed content of How to Convert a Java `java.util.Date` to a `java.sql.Date`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template