tags:

views:

105

answers:

3

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

+3  A: 

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)

Brian Agnew
Joda's Duration class is just a wrapper around a ms value and is not able to represent longer durations like "one day" correctly.
jarnbjo
True - but Joda provides both the `Duration` and `Period` classes to represent similar concepts. The latter isn't an exact number of milliseconds but can be "one day" or "one month", with their exact actual duration dependent on the start of the interval they're applied to.
Andrzej Doyle
...which actually is exactly what the OP was asking for if I understand his requirements correctly - http://joda-time.sourceforge.net/key_period.html
Andrzej Doyle
That does look a lot more relevant. I've edited to highlight the above.
Brian Agnew
+8  A: 

In .Net you can use the TimeSpan structure to represent a length of time.

tvanfosson
Many programmers don't know this structure exists because they don't see it represented in the native C# or VB.NET data types - voted you up - encouraging more people to do the same so this often missed data type is made well known.
John K
Of course, if you subtract or add dates in .NET, you get a TimeSpan back.
R. Bemrose
+1  A: 

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.

Sinuhe