Zerowalker
Zerowalker

Reputation: 767

Calculate Time Difference, and using Days

Okay i got a way to calculate the time Difference between 2 files, or rather 2 "dates". 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.

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.

Upvotes: 0

Views: 95

Answers (3)

saeed
saeed

Reputation: 2497

            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()+ ")";

Upvotes: 0

Marciano.Andrade
Marciano.Andrade

Reputation: 306

You can use the TimeSpan class to do that. 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.

Upvotes: 0

Douglas
Douglas

Reputation: 54877

Just perform the subtraction on the full dates (rather than their time components):

var difference = lastDt - firstDt;

Upvotes: 5

Related Questions