如何将字符串时间跨度变量从Wcf转换为小时和分钟?

How can I convert come string timespan variable from Wcf to hours and minutes?

本文关键字:转换 小时 分钟 Wcf 字符串 时间跨度 变量      更新时间:2023-09-26

我有一个变量是来自wcf的http调用javascript就像"P18DT5H"

c#:

param.time = new TimeSpan(18, 5, 0, 0);

我想转换小时和分钟?我应该使用正则表达式吗?

您可以使用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);

对于您的示例,它将返回,没有分钟:

437 hours, 0 minutes