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

試著忘記壹切 提交于 2019-12-12 00:32:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!