Home >Java >javaTutorial >How to Convert Between java.util.Date and java.sql.Date in Java?

How to Convert Between java.util.Date and java.sql.Date in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 20:13:17659browse

How to Convert Between java.util.Date and java.sql.Date in Java?

Java Date Conversion: Converting Between java.util.Date and java.sql.Date

When working with dates in Java, you may encounter the need to convert between java.util.Date and java.sql.Date. While you might expect implicit or explicit type conversion, the Java API requires an explicit conversion process. This guide will delve into the solution and provide a clear explanation of the code required.

The code snippet below demonstrates how you can convert a java.util.Date object to a java.sql.Date object:

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);

In this code, the following steps take place:

  1. Creating a java.util.Date object: Use new java.util.Date() to create an instance of java.util.Date, representing the current time.
  2. Getting the milliseconds: Invoke getTime() on the java.util.Date object to retrieve a long value representing the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT).
  3. Creating a java.sql.Date object: Pass the milliseconds to a new instance of java.sql.Date using the constructor java.sql.Date(long milliseconds).
  4. Printing the results: Use System.out.println to display the values of both java.util.Date and java.sql.Date objects for comparison.

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

Statement:
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