c# - 为什么这个日期时间方法会失败?

标签 c# unit-testing

我正在使用一个基本函数来获取小时、分钟和秒数。如果时间少于 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/

相关文章:

C# MVC Controller 调用两次

c# - 部分类中的utf-8错误

unit-testing - jUnit fail() 约定

java - 在 Junit Test 中覆盖默认 Spring-Boot application.properties 设置

c++ - 对采用 "traits"模板参数的对象进行单元测试

c# - 在 C# 中通过串口访问蓝牙数据

c# - 区分 Orchard CMS 内容部分驱动程序中的创建和更新

c# - 捆绑和缩小错误

unit-testing - 单元测试复杂逻辑

c++ - gtest 类型参数化的多态性