简体   繁体   English

计算时差,并使用天数

[英]Calculate Time Difference, and using Days

Okay i got a way to calculate the time Difference between 2 files, or rather 2 "dates". 好的,我有一种方法来计算2个文件之间的时间差,或者说是2个“日期”。 And it works, however, if the time difference is a day, meaning one starts at, let´s say 23:00, and the other 01:20 the next day, it will fail and think it´s behind rather than just 2 hours in front. 而且它是有效的,但是,如果时差是一天,这意味着一个开始于例如23:00,另一个在第二天01:20开始,它将失败并认为它落后于仅仅2前几个小时。

Here is the code: 这是代码:

private void button1_Click(object sender, EventArgs e)
{
   try
   {
       DateTime firstDt;
       DateTime lastDt;
       if (DateTime.TryParseExact(First.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out firstDt)
              && DateTime.TryParseExact(Last.Text, "yyyy-MM-dd HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out lastDt))
       {
          var difference = lastDt.TimeOfDay - firstDt.TimeOfDay;
          Console.WriteLine(difference);
          CalcDiff.Text = "DelayAudio(" + difference.TotalSeconds.ToString("F3") + ")";
       }
   }
   catch (Exception ex)
   {
      MessageBox.Show("TimeSpan Calculate: " + ex.Message);
   }
}

Not really sure how to make it use the Day, as it seems like it should do it. 不太确定如何使用Day,因为它似乎应该这样做。

只需对完整日期(而不是其时间分量)执行减法:

var difference = lastDt - firstDt;
            DateTime firstDt;
            DateTime lastDt;
            DateTime.TryParse(First.Text, out firstDt);
            DateTime.TryParse(Last.Text, out lastDt);
            TimeSpan difference = lastDt - firstDt;
            CalcDiff.Text = "DelayAudio(" + difference.ToString()+ ")";

You can use the TimeSpan class to do that. 您可以使用TimeSpan类来做到这一点。 For so, you need to substract a Date from another, like 为此,您需要减去另一个日期,例如

TimeSpan ts = lastDate - startDate;
Console.Write(ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds); // ts.ToString("HH:mm:ss") should work.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM