C# 将从反射中提取的timespan格式化为仅显示小时和分钟
我有一个函数,我将向其传递一个匿名对象,然后我必须返回一个timespan值,该值将以hh:mm格式显示。请查看下面的代码片段C# 将从反射中提取的timespan格式化为仅显示小时和分钟,c#,c#-4.0,tostring,timespan,typeconverter,C#,C# 4.0,Tostring,Timespan,Typeconverter,我有一个函数,我将向其传递一个匿名对象,然后我必须返回一个timespan值,该值将以hh:mm格式显示。请查看下面的代码片段 public string GetTime(Object obj, string propName) { TimeSpan? time = obj.Gettype().GetProperty(propName).GetValue(obj, null); return time.ToString(@"hh\:mm"); } 我在时间变量中得到了正确的值,当
public string GetTime(Object obj, string propName)
{
TimeSpan? time = obj.Gettype().GetProperty(propName).GetValue(obj, null);
return time.ToString(@"hh\:mm");
}
我在时间变量中得到了正确的值,当我尝试将其转换为字符串时,它表示no-ToString函数接受1个参数
我甚至尝试使用TimeSpan.parse进行转换,然后它允许我在这里进行转换,但它给了我错误的值作为输出
以下是我的时间跨度分析:
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?
没有