【问题标题】:format timespan which is extracted from reflections to display only hours and minutes格式化从反射中提取的时间跨度以仅显示小时和分钟
【发布时间】:2013-08-07 15:01:01
【问题描述】:

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

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 作为字符串获得完全精确的值。 所以请任何解决方法.........

【问题讨论】:

    标签: c# c#-4.0 tostring timespan typeconverter


    【解决方案1】:

    试试:

    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? 没有。

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多