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

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

DDD
DDDOriginal
2024-12-24 08:06:17469browse

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

Conundrum in Conversion: From java.util.Date to java.sql.Date

While utilizing a java.util.Date as an input source for a query, it may arise that a java.sql.Date is required instead. However, the inability to perform implicit or explicit conversions between these two data types poses a challenge, especially for those new to the Java API.

Fear not, the quest for conversion has been answered!

To effectively transform a java.util.Date into its java.sql.Date counterpart, employ the following code:

import java.util.Date;
import java.sql.Date;

public class ConversionMagic {

  public static void main(String[] args) {
    Date utilDate = new Date();
    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
    System.out.println("Initial java.util.Date: " + utilDate);
    System.out.println("Transformed java.sql.Date: " + sqlDate);
  }

}

This snippet encapsulates the conversion process, where the constructor of java.sql.Date expects the millisecond representation of the java.util.Date as its input.

The example output verifies the conversion:

Initial java.util.Date: Tue Aug 09 11:38:11 GMT+08:00 2022
Transformed java.sql.Date: 2022-08-09

The above is the detailed content of How to Convert java.util.Date to 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