Reputation: 20090
I am looking for a general pattern to factor out some common code: I need to implement algebra addition and subtraction between classes which have different properties with different arithmetics. One classic case is an interval which can be expressed in seconds, hours and minutes, which I have implemented with a class with three int properties.
For example, if I want to subtract to a period of 0 seconds, 0 minutes and 1 hour a period of 0 seconds, 30 minutes, 0 hours, I don't want to obtain a period of 0 seconds, -30 minutes, 1 hour.
I would need to code the add and subtract between the two time interval, is there any common pattern to code this algebra ? Should I look for a different representation?
Update
I have oversimplified the question, because my use case typically applies to periods of time expressed in years, month, days and combination of them. The difficulty is that the user thinks in terms of days, month, years and there is not an exact conversion possible (how many days have a month? well...that varies)
So the user knows he will want to compute something in 6M 3 days, and when the computation will occur I will apply that interval to a reference date, getting the right result. I have no way to transform 6M 3D in an a total amount of days, because that depends on which reference date you select, and this will vary over time.
Upvotes: 1
Views: 167
Reputation: 32719
For this sepcific use case, you might want to have a look at scala-time
Here's an extract of its README, showing the syntax that you can use:
(2.hours + 45.minutes + 10.seconds).millis
returns Long = 9910000
Upvotes: 2
Reputation: 692043
If what you want is a "normalized" display, i.e. have te max number of hours, then the max number of minutes, then the max number of seconds, I would simply store the duration as a number of seconds, and compute the number of hours/minutes/seconds it contains each time you want to format the duration:
private int durationInSeconds;
public int getHours() {
return durationInSeconds / (60 * 60);
}
public int getMinutes() {
return (durationInSeconds % (60 * 60)) / 60;
}
public int getSeconds() {
return durationInSeconds % 60;
}
public void subtract(Duration duration) {
if (duration.durationInSeconds > this.durationInSeconds) {
throw new IllegalArgumentException("can't handle negative durations")
}
this.durationInSeconds -= duration.durationInSeconds;
}
(not tested, but you should get the idea)
Note that joda-time has a Duration class that could suit your needs.
Upvotes: 1