0

I am using Java to interact with a MySQL database that contains Time type values. I can read this directly into Java Time objects by using the getTime() method from the ResultSet class.

How can I add a number of minutes to the current Time object?

I am not allowed to use Joda Time or other external libraries nor change the database types.

I have read everything I could find (this, this and many others) but none of the responses actually use Time objects.

Community
  • 1
  • 1
Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114

3 Answers3

4

Time extends Date so you can use the techniques involving the Date and Calendar APIs.

import static java.util.Calendar.MINUTE;

...

final Time t = ... your Time instance ...;
final Calendar c = Calendar.getInstance();
c.setTime(t);
c.add(MINUTE, 10);
t.setTime(c.getTimeInMillis());

...keeping your fingers crossed that this didn't mess up something with the time zones/daylight saving time transitions.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

Since SQL Time object only store milliseconds now (everything else is deprecated) you can simply convert it to a Calendar object and add minutes to that like so:

Time mySqlTimeObject = getTime();

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mySqlTimeObject.getTime());
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 10);

Time myNewSqlTimeObject = new Time(cal.get(Calendar.MILLISECOND));
Octoshape
  • 1,131
  • 8
  • 26
2

I think you can convert Time to java.util.Date, for example:

        Time time = new Time (12,1,1);
        Date date = new Date(time.getTime());

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, 10);


        time = new Time (cal.getTime().getTime());
djvazquez
  • 160
  • 9