Be careful. TimeSpan
is meant to measure an elapsed duration of time, while time
in SQL Server is specifically a time-of-day. These are two different concepts.
Sometimes these get mixed up. For example, DateTime.TimeOfDay
is a TimeSpan
type - which goes against its design. It's a reasonable compromise since there is no Time
type in .Net and it can fit.
But a TimeSpan
that is 24 hours or greater will not fit into a SQL Server time
field.
Also, a TimeSpan
is based on standard days. You can create one with TimeSpan.FromHours(26)
and it will represent "1 day and 2 hours". If you call TimeSpan.FromHours(26).ToString()
it will be "1.02:00:00"
.
If you're storing an elapsed duration of time (not a time of day), then use a TimeSpan
in .Net, but use an integer type in SQL Server. Decide what units you want precision for, and that will help you choose a data type.
For example, you can store the full precision of TimeSpan.Ticks
using a SQL Server bigint
type. But probably you will store TimeSpan.TotalSeconds
using an int
. When loading, you can use TimeSpan.FromSeconds
to get back to a TimeSpan
type.
Also be aware that a TimeSpan
can be negative, which represents moving backwards in time.
By the way, if you used the Noda Time library - these concepts would be separated for you in types called Duration
and LocalTime
.
If what you were after is a way to parse a string like "26:00:00"
you can't do that with a TimeSpan
. But you can use Noda Time:
// starting from this string
string s = "26:00:00";
// Parse as a Duration using the Noda Time Pattern API
DurationPattern pattern = DurationPattern.CreateWithInvariantCulture("H:mm:ss");
Duration d = pattern.Parse(s).Value;
Debug.WriteLine(pattern.Format(d)); // 26:00:00
// if you want a TimeSpan, you can still get one.
TimeSpan ts = d.ToTimeSpan();
Debug.WriteLine(ts); // 1.02:00:00
26
a valid value ? you should parse it as int and then check if it is more than 23 or not. Guess the value won't save in the database too if its more than 24 hrs – Drandell