Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge java.util.date with java.sql.Time

I have an extensive DATE-TIME conversion class, but i came across a scenario that i cannot resolve:

I have a java.util.date: Tue May 10 00:00:00 BST 2011
I have a java.sql.time: 03:58:44

I need to create a java.util.date: Tue May 10 03:58:44 BST 2011

The only approach i came up with is:

public static Date getDate(Date date, Time time) {
    Calendar calendar=Calendar.getInstance();
    calendar.set(date.getYear(), date.getMonth(), date.getDay(), time.getHours(), time.getMinutes(), time.getSeconds());
    return calendar.getTime();
}

Totally deprecated code, and does not work: java.lang.IllegalArgumentException at java.sql.Time.getYear(Unknown Source)

Any ideas?

like image 767
marcolopes Avatar asked Nov 28 '22 03:11

marcolopes


2 Answers

java.sql.Time is just a wrapper over the java.util.Date. You can use it as if you would add two java.util.Date objects.

For example, set Calendar to java.sql.Time:

calendar.setTime(time);

Now extract the hour/minute/seconds fields, i.e.:

calendar.get(Calendar.HOUR);

Next, set the Calendar to java.util.Date object and add these three fields to its time, i.e.:

calendar.add(Calendar.HOUR, hour);

And get the Date back:

calendar.getTime();
like image 163
acalypso Avatar answered Dec 04 '22 07:12

acalypso


Easiest way would be to just add the milli secs together to create a new date, ala

public static Date getDate(Date date, Time time) {
    return new Date(date.getTime() + time.getTime())
}
like image 30
vickirk Avatar answered Dec 04 '22 05:12

vickirk