How to take the difference of two time

Hi all,

I would like to take the difference of two time and if it is more than 30 minutes, I will take some action.

I had manage to convert the time to string as follow

dt1="2006/03/20 23:55"

dt2="2006/04/10 10:55"

May I know how to take the difference (dt2-dt1) and check if the difference is more than 30 minutes

Please help



Answer this question

How to take the difference of two time

  • freka586

    If dt1 and dt2 are date times, operator - returns a timespan.

    TimeSpan ts = dt2 - dt1;

    then you can check if it's > 30 min.



  • Patrick Grimme

    Convert.ToDateTime may work for these values. Obviously, that's the type you need to work with.



  • Joe Rappo

    Hi Florin,

    Thanks for your help. I got it.


  • Yavuz Bogazci

    A complete solution could be (you have to treat exceptions in the conversion also):

    string l_sDate1 = "2006/03/20 22:00";
    string l_sDate2 = "2006/03/20 23:00";

    DateTime l_objDate1 = DateTime.Parse(l_sDate1);
    DateTime l_objDate2 = DateTime.Parse(l_sDate2);

    TimeSpan l_objTime = l_objDate2 - l_objDate1;

    Console.WriteLine("Difference in hours: " + l_objTime.TotalHours);

  • Jaimi

    Hi,

    I had applied the method as shown below :

    DateTime dt1 = Convert.ToDateTime(file_str_current1);

    DateTime dt2 = Convert.ToDateTime(txn_time);

    TimeSpan ts = dt1 - dt2;

    The value of dt1 is "4/10/2006 01:52:11 PM"

    and the value of dt2 is "3/23/2006 06:51:00 AM"

    and the value of ts is "18.07:01:11"

    Do you know how to interpret this

    And how can I convert to minutes

    Thanks


  • Ivan Starr

    currently, dt1 and dt2 are string, can I convert it to datetime
  • How to take the difference of two time