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.
Legacy | Modern | Conversion |
---|---|---|
java.util.Date | java.time.Instant | java.util.Date.toInstant() java.util.Date.from( Instant ) |
java.sql.Date | java.time.LocalDate | java.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
Custom Thread Pool in Java 8 Parallel Stream
Recursively List Files in Java
Random Errors When Changing Series Using Jfreechart
How to Read and Write Excel File
How to Refer to the Current Type With a Type Variable
How to Hash a Password in Java
What Are Static Factory Methods
Can Java Finalize an Object When It Is Still in Scope
How Many Characters Can a Java String Have
Equals VS Arrays.Equals in Java
Capturing Stdout When Calling Runtime.Exec
How to List the Files Inside a Jar File
How to Call One Constructor from Another in Java
How to Add New Elements to an Array
Changing the Current Working Directory in Java