I have two objects: a java.sql.Date
and a java.sql.Time
.
What is the best way to merge them into single java.util.Date
?
In the database those columns are stored separately. I get them by JDBC rs.getDate("Date")
and rs.getTime("Time");
.
In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero. Basically, it's a wrapper around java. util. Date that handles SQL specific requirements.
sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.
If you compare to java. sql. Timestamp with equals() the method it will return false as value of nanosecond is unknown. That's all on the difference between java.
A thin wrapper around java. util. Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds.
You can create two Calendar instances. In the first you initialize the date and in the latter the time. You can the extract the time values from the "time" instance and set them to the "date".
// Construct date and time objects
Calendar dateCal = Calendar.getInstance();
dateCal.setTime(date);
Calendar timeCal = Calendar.getInstance();
timeCal.setTime(time);
// Extract the time of the "time" object to the "date"
dateCal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY));
dateCal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE));
dateCal.set(Calendar.SECOND, timeCal.get(Calendar.SECOND));
// Get the time value!
date = dateCal.getTime();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With