Tutorial :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


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)


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


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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »