Timespan and Databases

When you are developing application you may need to store timespan database. (Assuming you are using Sql Server 2005)

TimeSpan.TotalSeconds can be used to store. This returns a double. And maps to decimal data type of the sql server. For reverse action to get the time span you can use TimeSpan.FromSeconds method. This will give you the nearest millisecond value of the stored data.

But if you need accuracy you can use TimeSpan.Ticks method is suitable for you. This returns Int64 (long) and maps to bigint data type for to store in db.You can convert it to TimeSpan with the TimeSpan.FromTicks method.

“Using Ticks more accurate then FromSeconds”

Sample (.aspx page):

string startTime = "13:46:33.5268767";
string endTime = "13:47:03.1988761";
DateTime startDate = Convert.ToDateTime(startTime);
DateTime endDate = Convert.ToDateTime(endTime);

Response.Write(string.Format("Start Date : {0}<br/>", startDate));
Response.Write(string.Format("End Date : {0}<br/>", endDate));

TimeSpan timeSpan = endDate – startDate;
double timeSpanValue1 = timeSpan.TotalSeconds;
long timeSpanValue2 = timeSpan.Ticks;

Response.Write(string.Format("From Seconds : {0} (Rounded To Nearest Millisecond)<br/>",TimeSpan.FromSeconds(timeSpanValue1)));
Response.Write(string.Format("From Ticks : {0} (More Accurate)<br/>", TimeSpan.FromTicks(timeSpanValue2)));

Happy coding…

Posts created 141

Leave a Reply

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top