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!