开发者

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), s开发者_StackOverflow中文版econds 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜