我正在使用一个基本函数来获取小时、分钟和秒数。如果时间少于 24 小时,一切正常。我想获得小时数,即使它们超过 24 天而不是天数。
下面的示例生成: 00h:00m:00s
我的测试:
[TestMethod()]
public void Test_Hours_Greater_Than_24()
{
EmployeeSkill target = new EmployeeSkill(); appropriate value
double sec = 86400;
string expected = "24h:00m:00s";
string actual;
actual = target.GetAgentTime(sec);
Assert.AreEqual(expected, actual);
}
我的方法:
public string GetAgentTime(double sec)
{
TimeSpan t = TimeSpan.FromSeconds(sec);
return string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
t.Hours,
t.Minutes,
t.Seconds
);
}
最佳答案
尝试 t.TotalHours . t.Hours
将在达到一整天后结束,并相应地增加 t.Days
。
Gets the value of the current TimeSpan structure expressed in whole and fractional hours.
using System;
public class Example
{
public static void Main()
{
// Define an interval of 1 day, 15+ hours.
TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
Console.WriteLine("Value of TimeSpan: {0}", interval);
Console.WriteLine("{0:N5} hours, as follows:", interval.TotalHours);
Console.WriteLine(" Hours: {0,3}",
interval.Days * 24 + interval.Hours);
Console.WriteLine(" Minutes: {0,3}", interval.Minutes);
Console.WriteLine(" Seconds: {0,3}", interval.Seconds);
Console.WriteLine(" Milliseconds: {0,3}", interval.Milliseconds);
}
}
// The example displays the following output:
// Value of TimeSpan: 1.15:42:45.7500000
// 39.71271 hours, as follows:
// Hours: 39
// Minutes: 42
// Seconds: 45
// Milliseconds: 750
关于c# - 为什么这个日期时间方法会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371193/