I have read this question and seems rather long winded especially since I want to do quite a bit and avoid using the java.util.date types. I essentially want to be able to add and subtract arbitrary time values to a specific time like (0220 + 3hrs 45mins). The best I have is to convert the value to a "long" type then perform the arithmetic but I'm sure that's not the way to go. (possible overflows and inaccuracies when converting back?) Just need ideas on the best way to do this.
Asked
Active
Viewed 158 times
1 Answers
1
I think moving to a long
and then adding the appropriate number of milliseconds that represents "3 hours and 45 minutes" will work fine. There is no way to overflow it unless you are adding enough milliseconds to overflow the 64-bit long -- that's a lot of milliseconds.
long millis = time.getTime();
millis += 3 * 3600 * 1000;
millis += 45 * 60 * 1000;
time = new java.sql.Time(millis);
Another way to do it is to use the fabulous Joda Time methods which will be somewhat more expensive but certainly more readible/easy:
org.joda.time.DateTime dateTime = new DateTime(time.getTime());
dateTime = dateTime.plusHours(3).plusMinutes(45);
time = new java.sql.Time(dateTime.getMillis());

Gray
- 115,027
- 24
- 293
- 354
-
Thank you for the suggestion to use Joda – Dark Star1 Dec 02 '11 at 14:33