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
Both have time and day, so you could do something like:
Date d = new Date(2013, 11, 23);
Time t = new Time(23, 45, 45);
d.setMinutes(t.getMinutes());
d.setHours(t.getHours());
d.setSeconds(t.getSeconds());
The answer by istovatis is correct except for not carrying the milliseconds over. I should like to contribute the modern answer. java.sql.Date
and java.sql.Time
are now long outdated, and their replacements, the LocalDate
and LocalTime
classes, make your task much simpler. Assuming you are using Java 8 or later and JDBC 4.2 or higher, get those types from your result set and combine them:
LocalDate date = rs.getObject("Date", LocalDate.class);
LocalTime time = rs.getObject("Time", LocalTime.class);
LocalDateTime dateTime = date.atTime(time);
In case you don’t have direct access to your SQL result set and get java.sql.Date
and java.sql.Time
from some legacy API that you cannot change, I recommend you convert to the modern types and then use the same way of merging:
LocalDate date = sqlDate.toLocalDate();
LocalTime time = sqlTime.toLocalTime();
LocalDateTime dateTime = date.atTime(time);
You asked for a java.util.Date
. That class too is long outdated, so it’s better to use the LocalDateTime
from the above code (or perhaps convert to ZonedDateTime
or Instant
, depending on what you will be using it for). If you do need a Date
for some other legacy API that you cannot change either, convert like this:
Instant inst = dateTime.atZone(ZoneId.systemDefault()).toInstant();
java.util.Date utilDate = java.util.Date.from(inst);
If your legacy API required a Timestamp
object, it is even simpler:
Timestamp ts = Timestamp.valueOf(dateTime);
Link: Oracle tutorial: Date Time explaining how to use java.time
.
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();