Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling and storing elapsed time

I'm having problems deciding on what is the best way is to handle and store time measurements.

I have an app that has a textbox that allows the users to input time in either hh:mm:ss or mm:ss format.

So I was planning on parsing this string, tokenizing it on the colons and creating TimeSpan (or using TimeSpan.Parse() and just adding a "00:" to the mm:ss case) for my business logic. Ok?

How do I store this as in a database though? What would the field type be? DateTime seems wrong. I don't want a time of 00:54:12 to be stored as 1901-01-01 00:54:12 that seems a bit poor?

like image 916
Dan Avatar asked Sep 17 '08 16:09

Dan


3 Answers

TimeSpan has an Int64 Ticks property that you can store instead, and a constructor that takes a Ticks value.

like image 70
Jason DeFontes Avatar answered Oct 22 '22 15:10

Jason DeFontes


I think the simplest is to just convert user input into a integer number of seconds. So 54:12 == 3252 seconds, so store the 3252 in your database or wherever. Then when you need to display it to the user, you can convert it back again.

like image 20
davr Avatar answered Oct 22 '22 17:10

davr


For periods less than a day, just use seconds as other have said.

For longer periods, it depends on your db engine. If SQL Server, prior to version 2008 you want a datetime. It's okay- you can just ignore the default 1/1/1900 date they'll all have. If you are fortunate enough to have sql server 2008, then there are separate Date and Time datatypes you can use. The advantage with using a real datetime/time type is the use of the DateDiff function for comparing durations.

like image 45
Joel Coehoorn Avatar answered Oct 22 '22 17:10

Joel Coehoorn