如何将字符串时间跨度变量从 Wcf 转换为小时和分钟?
问题描述:
我有来自 wcf 的变量,通过 http 调用 javascript 就像P18DT5H"
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?
答
您可以使用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