问题
I have variable that is come from wcf with http call to javascript is like "P18DT5H"
C#:
param.time = new TimeSpan(18, 5, 0, 0);
I want to convert hours and minutes? Should I use regular expression?
回答1:
You can use ParseExact
:
string span = "P18DT5H";
IFormatProvider formatProvider = System.Globalization.CultureInfo.InvariantCulture;
TimeSpan timeSpan = TimeSpan.ParseExact(span, "'P'd'DT'h'H'", formatProvider);
int hours = (int)Math.Floor(timeSpan.TotalHours);
int minutes = (int)Math.Round(timeSpan.Subtract(new TimeSpan(hours, 0, 0)).TotalMinutes, 0, MidpointRounding.AwayFromZero);
Console.WriteLine("{0} hours, {1} minutes", hours, minutes);
It will return for your example with no minutes:
437 hours, 0 minutes
来源:https://stackoverflow.com/questions/32043550/how-can-i-convert-come-string-timespan-variable-from-wcf-to-hours-and-minutes