I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.
Right now I have a "old fashion style":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);
To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property.
Parse(String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan
is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt"
.
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Use TimeSpan.Parse
to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With