Home >Java >javaTutorial >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:
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);
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!