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

JavaJdbc

Java Problem Overview


What's the simplest way to convert a java.sql.Date object to a java.util.Date while retaining the timestamp?

I tried:

java.util.Date newDate = new Date(result.getDate("VALUEDATE").getTime());

with no luck. It's still only storing the date portion into the variable.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

If you really want the runtime type to be util.Date then just do this:

java.util.Date utilDate = new java.util.Date(sqlDate.getTime());

Brian.

Solution 3 - Java

Since java.sql.Date extends java.util.Date, you should be able to do

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

Solution 4 - Java

This function will return a converted java date from SQL date object.

public static java.util.Date convertFromSQLDateToJAVADate(
			java.sql.Date sqlDate) {
		java.util.Date javaDate = null;
		if (sqlDate != null) {
			javaDate = new Date(sqlDate.getTime());
		}
		return javaDate;
	}

Solution 5 - Java

From reading the source code, if a java.sql.Date does actually have time information, calling getTime() will return a value that includes the time information.

If that is not working, then the information is not in the java.sql.Date object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.

I think you should be using java.sql.Timestamp and the corresponding resultset methods, and the corresponding SQL type.

Solution 6 - Java

In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmservidioView Question on Stackoverflow
Solution 1 - Javax4uView Answer on Stackoverflow
Solution 2 - JavabrianbruffView Answer on Stackoverflow
Solution 3 - JavaBala RView Answer on Stackoverflow
Solution 4 - JavaTanmay kumar shawView Answer on Stackoverflow
Solution 5 - JavaStephen CView Answer on Stackoverflow
Solution 6 - JavaStanley ShiView Answer on Stackoverflow