繁体   English   中英

从反射中提取的格式时间跨度仅显示小时和分钟

[英]format timespan which is extracted from reflections to display only hours and minutes

我有一个函数,我将传递一个匿名对象,然后我必须返回一个时间跨度值,该值将以hh:mm格式显示该值。下面是我的代码段。

public string GetTime(Object obj, string propName)
{
   TimeSpan? time = obj.Gettype().GetProperty(propName).GetValue(obj, null);

   return time.ToString(@"hh\:mm");
}

我在时间变量中获得了正确的值,当我尝试将其转换为字符串时,它说没有ToString函数需要1个参数

我什至尝试通过使用TimeSpan.parse进行转换,然后它允许我在此处进行转换,但是它给了我错误的输出值

这是我的TimeSpan解析:

return TimeSpan.Parse(time.ToString()).ToString(@"hh\:mm");

一些我想如何将hh:mm作为字符串来获得完全精确的值。 所以请大家解决.........

尝试:

public string GetTime(Object obj, string propName)
{
   TimeSpan? time = obj.GetType().GetProperty(propName).GetValue(obj, null);

   // The difference is here... If time has a value, then take it
   // and format it, otherwise return an empty string.
   return time.HasValue ? time.Value.ToString(@"hh\:mm") : string.Empty;
}

TimeSpan.ToString()具有所需的重载时, TimeSpan? 没有。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM