Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine a java.util.Date object with a java.sql.Time object?

Tags:

java

date

time

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;
        }
like image 606
ScArcher2 Avatar asked Dec 05 '08 15:12

ScArcher2


3 Answers

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.

  Calendar dCal = Calendar.getInstance();
  dCal.setTime(date);
  Calendar tCal = Calendar.getInstance();
  tCal.setTime(time);
  dCal.set(Calendar.HOUR_OF_DAY, tCal.get(Calendar.HOUR_OF_DAY));
  dCal.set(Calendar.MINUTE, tCal.get(Calendar.MINUTE));
  dCal.set(Calendar.SECOND, tCal.get(Calendar.SECOND));
  dCal.set(Calendar.MILLISECOND, tCal.get(Calendar.MILLISECOND));
  date = dCal.getTime();
like image 150
Paul Tomblin Avatar answered Oct 05 '22 18:10

Paul Tomblin


Use Joda Time instead of Java's own Date classes when doing these types of things. It's a far superior date/time api that makes the sort of thing you are trying to do extremely easy and reliable.

like image 29
Steve McLeod Avatar answered Oct 05 '22 19:10

Steve McLeod


@Paul Tomblin is a sure way to control the TimeZone issue, and I knew someone was going to throw "Joda Time" into the mix. The other answers are all good and more robust than the following hack:

If your application executes in the same TimeZone as is the default in the DB, you might be able to get away with the following:

If you skip this step:

Date t = new Date(time.getTime());

and use the java.sql.Time value directly, like:

newDate = new Date(newDate.getTime() + time.getTime());

the conversion to the default TimeZone won't be introduced - the java.sql.Time should contain the value as stored.

YMMV, caveat emptor, etc...

like image 29
Ken Gentle Avatar answered Oct 05 '22 19:10

Ken Gentle