How to handle full period in java.time? - java

The Period class in java.time handles only the date-oriented potion: years, months, days.
What about the time portion: hours, minutes, seconds?
How can we parse and generate string representations of full periods as defined in ISO 8601, PnYnMnDTnHnMnS? For example, a day and a half: P1DT12H. The academic year is nine months, P9M. Every year I get two weeks and 3 days of vacation, P17D. The customer occupied the hotel room for 2 days and seventeen and a half hours, P2DT17H30M.
The Period class in Joda-Time handles full period. Why not in java.time? Is there some other mechanism?

In Java SE 8, it is the responsibility of the application to create a class linking Period and Duration if that is needed.
Note that a Duration contains an amount of seconds, not separate amounts of seconds, minutes and hours. The amount of seconds can exceed 24 hours, thus a Duration can represent a "day". But it is a fixed 24 hours day. By contrast, the representation of a "day in Period is descriptive and takes into account DST. The state of a Period is formed from three separate fields - days, months and years.
Bear in mind that "The customer occupied the hotel room for 2 days and seventeen and a half hours, P2DT17H30M" has the possibility to be complicated by DST cutovers. Using Period and Duration separately things are clear - Period is affected by DST cutovers and Duration is not.
In design terms, the original java.time Period did include hours, minutes and seconds. However, this resulted in the need for many methods and complicated Javadoc to describe all the possibilities around normalization and DST. By separating the concepts, the interaction of each with the timeline is a lot clearer. Note that the two classes also relate to the SQL design ("year to month" and "day to second" concepts).
There are no current plans to add a new class for Java SE 9in this area, however it cannot be completely ruled out because XML/ISO-8601 allows a single combined representation.

org.threeten.extra.PeriodDuration
The ThreeTen-Extra project offers a class combining a Period and a Duration. Simply called PeriodDuration.
An amount of time in the ISO-8601 calendar system that combines a period and a duration.
This class models a quantity or amount of time in terms of a Period and Duration. A period is a date-based amount of time, consisting of years, months and days. A duration is a time-based amount of time, consisting of seconds and nanoseconds. See the Period and Duration classes for more details.
The days in a period take account of daylight saving changes (23 or 25 hour days). When performing calculations, the period is added first, then the duration.
Caveat: Be sure to read the Answer by JodaStephen to understand the issues involved in trying to combine Period and Duration. It rarely makes sense to do so in practice, though that is counter to our intuition.
FYI, ThreeTen-Extra, java.time in JSR 310, and Joda-Time are all led by the same man, Stephen Colebourne a.k.a. JodaStephen.

Short answer related to java.time (JSR-310):
No, that package does not offer a solution.
Alternatively, you can use the class Duration in the package javax.xml.datatype for parsing strings like PnYnMnDTnHnMnS. This is also available in older JDK-versions since Java-5. Example:
// parsing
String iso = "P2Y4M30DT17H5M57.123S";
javax.xml.datatype.Duration xmlDuration =
DatatypeFactory.newInstance().newDuration(iso);
int years = xmlDuration.getYears();
int months = xmlDuration.getMonths();
int days = xmlDuration.getDays();
int hours = xmlDuration.getHours();
int minutes = xmlDuration.getMinutes();
int fullSeconds = xmlDuration.getSeconds();
BigDecimal seconds = (BigDecimal) xmlDuration.getField(DatatypeConstants.SECONDS);
// generating ISO-string
String xml = xmlDuration.toString();
System.out.println(xml); // P2Y4M30DT17H5M57.123S
If you ask for limitations/issues, well, here you get a list:
Some (alternative) ISO-formats like P0001-04-20T4H cannot be parsed.
Some methods defined in javax.xml.datatype.Duration rely on an internal Calendar-instance (documented) so that those methods might not work if an instance of Duration holds very large values.
Working with fractional seconds might be awkward and sometimes limited in precision if operating on a Calendar-instance.
There is only one single normalization method using a Calendar-instance. At least this method takes into account DST-effects in a standard way.
Formatting (not even to mention localized printing) is not offered.
If you want to overcome those issues then you can consider an external library (and yes, I don't only think of Joda-Time whose precision is constrained to millisecs and whose internationalization is limited, too). Otherwise the package javax.xml.datatype has the advantage to save the effort to embed an external library into your classpath.
Update:
About the question in comment related to external libraries, I know Joda-Time and my library Time4J.
First one (Joda-Time) offers a special class called ISOPeriodFormat. This class is also able to parse alternative ISO-formats (although PyyyyWwwddThhmmss is not mentioned in original ISO-8601-paper while support for PYYYY-DDD is missing). Joda-Time defines a builder-driven approach for period formatters which can also be used for printing durations (periods). Furthermore, there is a limited support for localized printing (with version 2.9.3 of Joda-Time in 13 languages). Finally the class Period offers various normalization methods (see javadoc).
Second one (Time4J) offers the classes net.time4j.Duration and two formatting tools (Duration.Formatter for pattern-based printing/parsing and net.time4j.PrettyTime for localized printing in actually 78 languages). The class Duration offers for parsing ISO-strings the static method parsePeriod(String) and also various normalizing methods. Example for the interoperability with java.time (JSR-310) proving that this library can be considered and used as powerful extension of new java-8-date-time-api:
// input: using java.time-package
LocalDateTime start = LocalDateTime.of(2016, 3, 7, 10, 15, 8);
LocalDateTime stop = LocalDateTime.of(2016, 6, 1, 22, 15);
// define how you measure the duration (zone correction would also be possible)
Duration<?> duration =
TimestampInterval.between(start, stop).getDuration(
CalendarUnit.YEARS,
CalendarUnit.MONTHS,
CalendarUnit.DAYS,
ClockUnit.HOURS,
ClockUnit.MINUTES,
ClockUnit.SECONDS
);
// generate standard ISO-representation
String s = duration.toStringISO();
System.out.println(s); // P2M25DT11H59M52S
// parse ISO-String and prove equality with original
System.out.println(Duration.parsePeriod(s).equals(duration)); // true
// adding duration to <start> yields <stop>
System.out.println(start.plus(duration.toTemporalAmount())); // 2016-06-01T22:15
// format in human time
System.out.println(PrettyTime.of(Locale.US).print(duration));
// output: 2 months, 25 days, 11 hours, 59 minutes, and 52 seconds
For completeness I should also mention ocpsoft.PrettyTime but I am not sure if that library is able to process ISO-strings. It is rather designed for relative times.

Related

Subtleties between Java Period and Duration

I'm not sure I'm getting the subtleties between Java Period and Duration.
When I read Oracle's explanation, it says that I can find out how many days since a birthday like this (using the example dates they used):
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period birthdayPeriod = Period.between(birthday, today);
int daysOld = birthdayPeriod.getDays();
But as even they point out, this doesn't take into account the time zone you were born in and the time zone you are in now. But this is a computer and we can be precise, right? So would I use a Duration?
ZoneId bornIn = ZoneId.of("America/New_York");
ZonedDateTime born = ZonedDateTime.of(1960, Month.JANUARY.getValue(), 1, 2, 34, 56, 0, bornIn);
ZonedDateTime now = ZonedDateTime.now();
Duration duration = Duration.between(born, now);
long daysPassed = duration.toDays();
Now the actual times are accurate, but if I understand this correctly, the days might not correctly represent calendar days, e.g. with DST and such.
So what am I do to to get a precise answer based upon my time zone? The only thing I can think of is to go back to using LocalDate, but normalize the time zones first from the ZonedDateTime values, and then use a Duration.
ZoneId bornIn = ZoneId.of("America/New_York");
ZonedDateTime born = ZonedDateTime.of(1960, Month.JANUARY.getValue(), 1, 2, 34, 56, 0, bornIn);
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime nowNormalized=now.withZoneSameInstant(born.getZone());
Period preciseBirthdayPeriod = Period.between(born.toLocalDate(), nowNormalized.toLocalDate());
int preciseDaysOld = preciseBirthdayPeriod.getDays();
But that seems really complicated just to get a precise answer.
Your analysis regarding the Java-8-classes Period and Duration is more or less correct.
The class java.time.Period is limited to calendar date precision.
The class java.time.Duration only handles second (and nanosecond) precision but treats days always as equivalent to 24 hours = 86400 seconds.
Normally it is completely sufficient to ignore clock precision or timezones when calculating the age of a person because personal documents like passports don't document the exact time of day when someone was born. If so then the Period-class does its job (but please handle its methods like getDays() with care - see below).
But you want more precision and describe the result in terms of local fields taking into account timezones. Well, the first part (precision) is supported by Duration, but not the second part.
It is also not helpful to use Period because the exact time difference (which is ignored by Period) can impact the delta in days. And furthermore (just printing the output of your code):
Period preciseBirthdayPeriod =
Period.between(born.toLocalDate(), nowNormalized.toLocalDate());
int preciseDaysOld = preciseBirthdayPeriod.getDays();
System.out.println(preciseDaysOld); // 13
System.out.println(preciseBirthdayPeriod); // P56Y11M13D
As you can see, it is quite dangerous to use the method preciseBirthdayPeriod.getDays() in order to get the total delta in days. No, it is only a partial amount of the total delta. There are also 11 months and 56 years. I think it is wise to also print the delta not only in days because then people can easier imagine how big the delta is (see the often seen use-case of printed durations in social media like "3 years, 2 months, and 4 days").
Obviously, you rather need a way to determine a duration including calendar units as well as clock units in a special timezone (in your example: the timezone where someone has been born). The bad thing about Java-8-time-library is: It does not support any combination of Period AND Duration. And importing the external library Threeten-Extra-class Interval will also not help because long daysPassed = interval.toDuration().toDays(); will still ignore timezone effects (1 day == 24 hours) and is also not capable of printing the delta in other units like months etc.
Summary:
You have tried the Period-solution. The answer given by #swiedsw tried the Duration-based solution. Both approaches have disadvantages with respect to precision. You could try to combine both classes in a new class which implements TemporalAmount and realize the necessary time arithmetic yourself (not so trivial).
Side note:
I have myself already implemented in my time library Time4J what you look for, so it might be useful as inspiration for your own implementation. Example:
Timezone bornZone = Timezone.of(AMERICA.NEW_YORK);
Moment bornTime =
PlainTimestamp.of(1960, net.time4j.Month.JANUARY.getValue(), 1, 22, 34, 56).in(
bornZone
);
Moment currentTime = Moment.nowInSystemTime();
MomentInterval interval = MomentInterval.between(bornTime, currentTime);
MachineTime<TimeUnit> mt = interval.getSimpleDuration();
System.out.println(mt); // 1797324427.356000000s [POSIX]
net.time4j.Duration<?> duration =
interval.getNominalDuration(
bornZone, // relevant if the moments are crossing a DST-boundary
CalendarUnit.YEARS,
CalendarUnit.MONTHS,
CalendarUnit.DAYS,
ClockUnit.HOURS,
ClockUnit.MINUTES
);
// P56Y11M12DT12H52M (12 days if the birth-time-of-day is after current clock time)
// If only days were specified above then the output would be: P20801D
System.out.println(duration);
System.out.println(duration.getPartialAmount(CalendarUnit.DAYS)); // 12
This example also demonstrates my general attitude that using units like months, days, hours etc. is not really exact in strict sense. The only strictly exact approach (from a scientific point of view) would be using the machine time in decimal seconds (best in SI-seconds, also possible in Time4J after the year 1972).
The JavaDoc of Period states that it models:
A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
I understand it has no reference to points in time.
You might want to check Interval from project ThreeTen-Extra which models:
an immutable interval of time between two instants.
The project website states the project “[...] is curated by the primary author of the Java 8 date and time library, Stephen Colebourne”.
You can retrieve a Duration from an Interval by invoking toDuration() on it.
I shall transform your code to give an example:
ZoneId bornIn = ZoneId.of("America/New_York");
ZonedDateTime born = ZonedDateTime.of(1960, Month.JANUARY.getValue(), 1, 2, 34, 56, 0, bornIn);
ZonedDateTime now = ZonedDateTime.now();
Interval interval = Interval.of(born.toInstant(), now.toInstant());
long daysPassed = interval.toDuration().toDays();
The main distinction between the two classes is :
that java.time.Period uses date-based values ( May 31, 2018)
while java.time.Duration is more precise, it uses time-based values ( "2018-05-31T11:45:20.223Z" )
java.time.Period is more friendly for human reading
for example Period between A and B is 2 years 3 months 3 days
java.time.Duration is for a machine.

Converting duration to years in Java8 Date API?

I have a date in the far past.
I found out what the duration is between this date and now.
Now I would like to know - how much is this in years?
I came up withthis solution using Java8 API.
This is a monstrous solution, since I have to convert the duration to Days manually first, because there will be an UnsupportedTemporalTypeException otherwise - LocalDate.plus(SECONDS) is not supported for whatever reason.
Even if the compiler allows this call.
Is there a less verbous possibility to convert Duration to years?
LocalDate dateOne = LocalDate.of(1415, Month.JULY, 6);
Duration durationSinceGuss1 = Duration.between(LocalDateTime.of(dateOne, LocalTime.MIDNIGHT),LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(),
LocalDate.now().plus(
TimeUnit.SECONDS.toDays(
durationSinceGuss1.getSeconds()),
ChronoUnit.DAYS) );
/*
* ERROR -
* LocalDate.now().plus(durationSinceGuss1) causes an Exception.
* Seconds are not Supported for LocalDate.plus()!!!
* WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss) );
/*
* ERROR -
* Still an exception!
* Even on explicitly converting duration to seconds.
* Everything like above. Seconds are just not allowed. Have to convert them manually first e.g. to Days?!
* WHY OR WHY CAN'T YOU CONVERT SECONDS TO DAYS OR SOMETHING AUTOMATICALLY, JAVA?
*/
//long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDate.now(), LocalDate.now().plus(durationSinceGuss.getSeconds(), ChronoUnit.SECONDS) );
Have you tried using LocalDateTime or DateTime instead of LocalDate? By design, the latter does not support hours/minutes/seconds/etc, hence the UnsupportedTemporalTypeException when you try to add seconds to it.
For example, this works:
LocalDateTime dateOne = LocalDateTime.of(1415, Month.JULY, 6, 0, 0);
Duration durationSinceGuss1 = Duration.between(dateOne, LocalDateTime.now());
long yearsSinceGuss = ChronoUnit.YEARS.between(LocalDateTime.now(), LocalDateTime.now().plus(durationSinceGuss1) );
System.out.println(yearsSinceGuss); // prints 600
Although the accepted answer of #Matt Ball tries to be clever in usage of the Java-8-API, I would throw in following objection:
Your requirement is not exact because there is no way to exactly convert seconds to years.
Reasons are:
Most important: Months have different lengths in days (from 28 to 31).
Years have sometimes leap days (29th of February) which have impact on calculating year deltas, too.
Gregorian cut-over: You start with a year in 1415 which is far before first gregorian calendar reform which cancelled full ten days, in England even 11 days and in Russia more. And years in old Julian calendar have different leap year rules.
Historic dates are not defined down to second precision. Can you for example describe the instant/moment of the battle of Hastings? We don't even know the exact hour, just the day. Assuming midnight at start of day is already a rough and probably wrong assumption.
Timezone effects which have impact on the length of day (23h, 24h, 25h or even different other lengths).
Leap seconds (exotic)
And maybe the most important objection to your code:
I cannot imagine that the supplier of the date with year 1415 has got the intention to interprete such a date as gregorian date.
I understand the wish for conversion from seconds to years but it can only be an approximation whatever you choose as solution. So if you have years like 1415 I would just suggest following very simple approximation:
Duration d = ...;
int approximateYears = (int) (d.toDays() / 365.2425);
For me, it is sufficient in historic context as long as we really want to use a second-based duration for such an use-case. It seems you cannot change the input you get from external sources (otherwise it would be a good idea to contact the duration supplier and ask if the count of days can be supplied instead). Anyway, you have to ask yourself what kind of year definition you want to apply.
Side notes:
Your complaint "WHY OR WHY CAN'T JAVA DO WHAT COMPILER ALLOWS ME TO DO?" does not match the character of new java.time-API.
You expect the API to be type-safe, but java.time (JSR-310) is not designed as type-safe and heavily relies on runtime-exceptions. The compiler will not help you with this API. Instead you have to consult the documentation in case of doubt if any given time unit is applicable on any given temporal type. You can find such an answer in the documentation of any concrete implementation of Temporal.isSupported(TemporalUnit). Anyway, the wish for compile-safety is understandable (and I have myself done my best to implement my own time library Time4J as type-safe) but the design of JSR-310 is already set in stone.
There is also a subtile pitfall if you apply a java.time.Duration on either LocalDateTime or Instant because the results are not exactly comparable (seconds of first type are defined on local timeline while seconds of Instant are defined on global timeline). So even if there is no runtime exception like in the accepted answer of #Matt Ball, we have to carefully consider if the result of such a calculation is reasonable and trustworthy.
Use Period to get the number of years between two LocalDate objects:
LocalDate before = LocalDate.of(1415, Month.JULY, 6);
LocalDate now = LocalDate.now();
Period period = Period.between(before, now);
int yearsPassed = period.getYears();
System.out.println(yearsPassed);

Java 8 -- How do I calculate (milli)seconds from now using xsd:duration

I feel like this question has been asked in one way or another, but I'm still not confident of my result.
I have an xsd:duration which will give me a desired expiration described in years, months, days, and seconds. I can collect the integer values of these parts with, for example, duration.getYears() or duration.getMonths().
Because my chosen db is Cassandra, I want to exploit the TTL option, which will automatically expire an inserted row after a specified number of seconds.
The critical part is getting from xsd:duration to an integer/long value of seconds which respects the Gregorian calendar (where 1 month from now is not simply 30.41 days, but 31).
At the moment, I'm using the following code:
LocalDateTime then = LocalDateTime.now().plusYears(duration.getYears()).plusMonths(duration.getMonths()).plusDays(duration.getDays()).plusHours(duration.getHours()).plusMinutes(duration.getMinutes()).plusSeconds(duration.getSeconds());
long ttlMillis = then.toInstant(ZoneOffset.UTC).toEpochMilli() - Instant.now().toEpochMilli();
Is there a quicker/cleaner way to do this?
I'm also not sure if I should worry about large durations... My particular use cases wouldn't call for anything larger that 2 years.
Informational note for all:
You are talking about javax.xml.datatype.Duration, not java.time.Duration.
Your questions:
a) Is there a quicker way to do this (using Java-8)? Hardly. The designers of JSR-310-team responsible for the new date- and time library in Java-8 have not cared much about the bridge to the existing XML-classes in JDK. So there is no direct way to convert from xml-duration to any kind of JSR-310-duration.
Keep also in mind that the JSR-310-classes Period (with state consisting of years, months and days) and Duration (with state consisting of seconds and nanoseconds) are not really designed for representing an xml-duration (which has more units as seen in your code). So I doubt if we might see a well-defined bridge between JSR-310 and XML in the future (maybe only on millisecond base?). The sign handling is also completely different in JSR-310 and XML. So be cautious if you have negative sign in xml-duration.
b) Is there a cleaner way to do this (using Java-8)? Yes, a little bit. One thing to consider is: I would use the clock as time source for the actual instant only once and not twice as you have done it. Example for this (very) minor improvement:
Instant now = Instant.now();
LocalDateTime start = now.atOffset(ZoneOffset.UTC).toLocalDateTime();
LocalDateTime end =
start.plusYears(duration.getYears())
.plusMonths(duration.getMonths())
.plusDays(duration.getDays())
.plusHours(duration.getHours())
.plusMinutes(duration.getMinutes())
.plusSeconds(duration.getSeconds());
long deltaInMillis = end.toInstant(ZoneOffset.UTC).toEpochMilli() - now.toEpochMilli();
Second thing to consider: The xml-duration class is designed for interoperation with java.util.Date. So you also have this short alternative:
Date start = new Date();
long deltaInMillis = duration.getTimeInMillis(start);
This alternative is not only much shorter, but is probably also more precise because it takes into account the millisecond part. According to the documentation you should only worry about the correctness if you have duration items in long range (excessing the range of int). Another topic is the relationship to any hidden timezone calculation. I have not seen any hint in the documentation, so this is maybe the only item which can make you worry (either local timezone? or UTC? - not tested).
c) Why worry about large durations? Even if your duration is larger than let's say some centuries possibly crossing the validity limits of historic gregorian calendar, you should keep in mind that xml-duration only uses the proleptic gregorian calendar, not the historical one. And LocalDateTime uses the same proleptic gregorian calendar, too. If such a large duration is related to any real data is another good question however.

Formatting a Duration in Java 8 / jsr310

I am transitioning a project from Joda-Time to java8's native time libraries, and I have run into a snag.
I have been unable to find a formatter for Duration. I would like to have a custom String format of, for instance, HHH+MM, where a Duration of 75 hours and 15 minutes would format as "75+15".
This was easy to do with Joda-Time by converting to period, and using a PeriodFormatter, but I have been unable to find this type of class in Java8. Am I missing something?
Java 9 and later: Duration::to…Part methods
In Java 9 the Duration class gained new to…Part methods for returning the various parts of days, hours, minutes, seconds, milliseconds/nanoseconds. See this pre-release OpenJDK source code.
Given a duration of 49H30M20.123S…
toNanosPart() = 123000000
toMillisPart() = 123
toSecondsPart() = 20
toMinutesPart() = 30
toHoursPart() = 1
toDaysPart() = 2
Remember that “days” here means chunks of 24-hours, ignoring dates on a calendar. If you care about dates, use Period class instead.
I do not know if any additional formatter features are added. But at least you will be able to more conveniently generate your own strings from numbers obtained via these new getter methods.
Java 8
Oddly enough, no convenient getter methods for these values were included in the first edition release of java.time in Java 8. One of very few oversights in the otherwise excellent design of the java.time framework.
See the related Question: Why can't I get a duration in minutes or hours in java.time?.
There is no period/duration-formatter in jsr-310, different from JodaTime. Not every feature of JodaTime was ported to JSR-310 (for example also not PeriodType). And in reverse JSR-310 has some features which are not available in JodaTime (for example localized weekday numbers or the strategy pattern approach with adjusters).
It might happen that Java 9 will introduce some kind of built-in period formatting (read something about this from S. Colebourne).
Conclusion: JSR-310 and JodaTime are not fully compatible to each other, so a lot of work can be required. I would not be so keen on migration as soon as possible. Do you need special features of JSR-310 which are not offered by JodaTime?
Additional note: You should also be aware of the fact that joda period (which includes all units from years to seconds) is not fully compatible with jsr310-period (only years, months, days) or jsr310-duration (only hours, minutes, seconds and fraction seconds).
There is no built-in method but you can access the number of hours/minutes without having to calculate them manually. Your specific format could look like:
Duration d = Duration.of(75, HOURS).plusMinutes(15);
long hours = d.toHours(); //75
long minutes = d.minusHours(hours).toMinutes(); //15
String HH_PLUS_MM = hours + "+" + minutes; //75+15
System.out.println(HH_PLUS_MM);
If the duration is guaranteed to be less than 24 hours, you can also use this trick:
String hhPlusMm = LocalTime.MIDNIGHT.plus(d).format(DateTimeFormatter.ofPattern("HH+mm"));
you can use the DurationFormatUtils from commons-lang3-time (for minutes you have to use "mm" as the format is the same as in SimpleDateFormat):
DurationFormatUtils.formatDuration(interval.toMillis(), "HHH+mm")
Sadly I found no way to exclude empty parts, like in my case days or hours could be 0, so I still had to roll my own.
Update: I have opened an issue for this on Apache commons.lang.time.DurationFormatUtils JIRA.
I know this is an old question but I recently ran into the same thing. There really should be a better solution than this, but this worked for me:
public static String millisToElapsedTime(long millis){
DateFormat fmt = new SimpleDateFormat(":mm:ss.SSS");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return (millis/3600000/*hours*/)+fmt.format(new Date(millis));
}
Then, you could add this:
public static String durationToElapsedTime(Duration d){
return millisToElapsedTime(d.toMillis());
}

Best Duration type in Java or .Net

I have seen way to many places where a method takes a long or an int to represent durations in either nanoseconds, milliseconds (most common), seconds and even days. This is a good place to look for errors, too.
The problem is also quite complex once you realize that you can mean for the duration to be a certain number of seconds, or an interval that fits the human perception of time better, so that a duration of 24 hours is always going to be the next day at the same "wall-clock" time. Or that a year is either 365 or 366 days depending on the date, so that a year from 28th of February is always going to be the 28th of February.
Why is there no distinct type to represent this? I have found none in either Java or .net
In .Net you can use the TimeSpan structure to represent a length of time.
For Java, take a look at Joda (an intuitive and consistent date/time library) and its Duration and Period classes. DateTime objects can handle addition and manipulation via these objects.
(answer changed to reflect the comments below re. the Period class)
It's not an easy problem. Maybe Joda-Time would be a useful library for you. It has a Duration class that can do what you are asking for.

Categories

Resources