How do I read a time value and then insert it into a TimeSpan variable
Question
How do I read a time value and then insert it into a TimeSpan variables?
Solution
If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?
So.. something like this?
string input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
OTHER TIPS
From MSDN: A TimeSpan object represents a time interval, or duration of time, measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The largest unit of time used to measure duration is a day.
Here's how you can initialize it to CurrentTime (in ticks):
TimeSpan ts = new TimeSpan(DateTime.Now.Ticks);
TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);
Or, if you mean DateTime:
DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);
Where all of the parameters are ints.
Perhaps using:
var span = new TimeSpan(hours, minutes, seconds);
If you mean adding two timespans together use:
var newSpan = span.Add(new TimeSpan(hours, minutes, seconds));
For more information see msdn.
You can't change the properties of a TimeSpan. You need to create a new instance and pass the new values there.