I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?
Parse(String, IFormatProvider) Converts the string representation of a time interval to its TimeSpan equivalent by using the specified culture-specific format information.
Split the string into its component parts. Get the number of minutes from the conversion table. Multiply that by the number and that is the number of minutes. Convert that to whatever format you need for the display.
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.
ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
This seems to work, though it is a bit hackish:
TimeSpan span; if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span)) MessageBox.Show(span.ToString());
DateTime.ParseExact
or DateTime.TryParseExact
lets you specify the exact format of the input. After you get the DateTime
, you can grab the DateTime.TimeOfDay
which is a TimeSpan
.
In the absence of TimeSpan.TryParseExact
, I think an 'elegant' solution is out of the mix.
@buyutec As you suspected, this method would not work if the time spans have more than 24 hours.
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