How to Convert Java.Util.Date to Java.Sql.Date

How to convert java.util.Date to java.sql.Date?

tl;dr

How to convert java.util.Date to java.sql.Date?

Don’t.

Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.

  • Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
  • Convert to/from java.time if inter-operating with code not yet updated to java.time.





















LegacyModernConversion
java.util.Datejava.time.Instantjava.util.Date.toInstant()
java.util.Date.from( Instant )
java.sql.Datejava.time.LocalDatejava.sql.Date.toLocalDate()
java.sql.Date.valueOf( LocalDate )

Convert from java.util.Date to java.sql.Date

java.util.Date d = new java.util.Date();
java.sql.Date sd = new java.sql.Date(d.getTime());

Conversion to java.sql.Date

java.sql.Date only provides the date.. You need to use java.sql.Timestamp to get both date and time.

java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date = format.parse("2017-08-31 01:40:00+00:00");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp);

How to cast java.util.date to java.sql.date?

No. You cannot cast different type of Objects like that.

instead you can get the time which is long and use it.

java.sql.Date sDate = new java.sql.Date(date.getTime());

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");


Related Topics



Leave a reply



Submit