I’m pulling back a Date and a Time from a database. They are stored in separate fields, but I would like to combine them into a java.util.Date object that reflects the date/time appropriately.
Here is my original approach, but it is flawed. I always end up with a Date/Time that is 6 hours off what it should be. I think this is because the Time has a timezone offset as well as the Date, and I really only need one of them to have the timezone offset.
Any suggestions on how to do this so that it will give me the correct Date/Time?
import java.sql.Time; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.time.DateUtils; public static Date combineDateTime(Date date, Time time) { if (date == null) return null; Date newDate = DateUtils.truncate(date, Calendar.DATE); if (time != null) { Date t = new Date(time.getTime()); newDate = new Date(newDate.getTime() + t.getTime()); } return newDate; }
I would put both the Date and the Time into Calendar objects, and then use the various Calendar methods to extract the time values from the second object and put them into the first.