代码之家  ›  专栏  ›  技术社区  ›  SyncMaster

两个时间间隔之间的差异查找问题

  •  1
  • SyncMaster  · 技术社区  · 14 年前

    我怎样才能找出两个时间间隔之间的区别呢? 如13:45:26.836-14:24:18.473,格式为“小时:分:秒:毫秒”。现在我需要找出这两次的时差。

    我怎么能用C来做这个?

    事先谢谢。

    4 回复  |  直到 14 年前
        1
  •  4
  •   marc_s    14 年前

    基本上,您需要做的是将这些时间值放入 DateTime 结构。一旦你有了你的两个 日期时间 变量,只需将它们相减-结果是一个类型的变量 TimeSpan :

    DateTime dt1 = new DateTime(2010, 5, 7, 13, 45, 26, 836);
    DateTime dt2 = new DateTime(2010, 5, 7, 14, 24, 18, 473);
    
    TimeSpan result = dt2 - dt1;
    string result2 = result.ToString();
    

    TimeSpan有许多属性可以获取集合-各种单位的差异,例如毫秒、秒、分钟等。您还可以执行 .ToString() 获取结果的字符串表示形式。在 result2 你会得到这样的结果:

    00:38:51.6370000
    

    这就是你要找的吗?

        2
  •  1
  •   berkay    14 年前

    我在张贴一个例子;

    你可以检查它并调整你的程序,

    /* Read the initial time. */
        DateTime startTime = DateTime.Now;
        Console.WriteLine(startTime);
    
        /* Do something that takes up some time. For example sleep for 1.7 seconds. */
        Thread.Sleep(1700);
    
        /* Read the end time. */
        DateTime stopTime = DateTime.Now;
        Console.WriteLine(stopTime);
    
        /* Compute the duration between the initial and the end time. 
         * Print out the number of elapsed hours, minutes, seconds and milliseconds. */
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("hours:" + duration.Hours);
        Console.WriteLine("minutes:" + duration.Minutes);
        Console.WriteLine("seconds:" + duration.Seconds);
        Console.WriteLine("milliseconds:" + duration.Milliseconds);
    
        3
  •  0
  •   Pran    14 年前

    找出秒数,减去这两个数字,你就可以算出时间差。根据您使用的编程语言,我肯定他们一定是可以处理它的库。

        4
  •  0
  •   Igor Zevaka    14 年前
    //Start off with a string
    string time1s = "13:45:26.836";
    string time2s = "14:24:18.473";
    
    TimeSpan interval = DateTime.Parse(time2s) - DateTime.Parse(time1s);
    

    这将产生以下结果:

      Days    0   int         Hours   0   int
      Milliseconds    637 int
      Minutes 38  int         Seconds 51  int
      Ticks   23316370000 long
      TotalDays   0.02698653935185185 double
      TotalHours  0.64767694444444446 double
      TotalMilliseconds   2331637.0   double
      TotalMinutes    38.860616666666665  double
      TotalSeconds    2331.6369999999997  double