在 .Net 中,有没有办法转换成'2:45'十进制的 2.75?
前任:
decimal d = TimeToDecimal("2:45");
Console.WriteLine(d);
//output is 2.75
如果无效数据,例如,分钟 < 0 < 60 或不是 h:m 格式,它应该抛出异常。
谢谢
在 .Net 中,有没有办法转换成'2:45'十进制的 2.75?
前任:
decimal d = TimeToDecimal("2:45");
Console.WriteLine(d);
//output is 2.75
如果无效数据,例如,分钟 < 0 < 60 或不是 h:m 格式,它应该抛出异常。
谢谢
以下将输出2.75:
TimeSpan time = TimeSpan.Parse("2:45");
decimal d = (decimal) time.TotalHours;
Console.WriteLine(d);
请注意,该TimeSpan.TotalHours属性是 type double,而不是decimal。
从该TimeSpan.Parse方法的文档中,它将抛出一个OverflowExceptionif “天、小时、分钟或秒组件中的至少一个超出其有效范围”,因此应该为您处理输入验证。另见TimeSpan.TryParse方法。
private decimal TimeToDecimal(string Time)
{
    DateTime dt = DateTime.Parse(Time);
    decimal result = dt.Hour+ (dt.Minute / 60.0m);
    return result;
}