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 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.