开发者

What is a meaningfull datatype to save hours

What is a good data-type for saving hours in .net?

Is it better to use the decimal type or is the double data-type more appropriate. With hours I mean values such as:


A good way to represent a number of hours is to use a TimeSpan:

TimeSpan hours = TimeSpan.FromHours(2);

Given the choice between decimal or double I'd probably go for double as there is typically no expectation that the amount of time is represented exactly. If you need an exact decimal representation of your fractional number of hours (which seems unlikely) then use decimal.

You could also consider storing it as an integer in for example seconds, milliseconds or ticks.


The best datatype to store hours is the one designed for it - TimeSpan.

It has methods that allow you to add/subtract/convert it.

As for storage in a database, it really depends on what you are using this for and what kind of resolution is required.

I would use the time datatype - as it will hold the range:

00:00:00.0000000 through 23:59:59.9999999

However, if you need to hold more than 24 hours in this field, you may want to consider a tinyint or int holding the number of minutes (assuming that is the maximum time resolution you require).


In SQL Server use INT or DECIMAL. TIME isn't really ideal for storing a duration because TIME defines a point in time within the 24 hour clock whereas duration is simply an integer or decimal value. You cannot do addition or subtraction with TIME values and there is no obvious way to use TIME to store durations greater than 24hrs.


Why don't use TIME?

You can use DATEADD with TIME to manipulate it easier:

SELECT DATEADD(minute, 30, CAST('2:00:00' AS TIME))

becomes 02:30:00.0000000. And so on..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜