0

data table have two columns of From Date and two Date with the date time datatype and i need to calculate two times differences how can i do this

Robert E
  • 87
  • 11
  • Make a loop of data table and get two dates after that calculate difference. What do you want? Do you want number of days difference? – Venkateswaran R Apr 11 '17 at 09:05
  • "Calculate two times differences", difference to what? What have you tried? If you subtract one DateTime from another you'll get a `TimeSpan` which is what you need. – Tim Schmelter Apr 11 '17 at 09:09
  • Difference is calculated by subtracting ToDate from FromDate – Renatas M. Apr 11 '17 at 09:12

2 Answers2

0

You can either do this in c# like this

DateTime dtFrom = Convert.toDateTime(aReader["fromDate"]);
DateTime dtTo = Convert.toDateTime(aReader["ToDate"]);
TimeSpan span = dtFrom - dtTo;
Console.WriteLine("Difference (seconds)" + span.Seconds );
Console.WriteLine("Difference (minutes)" + span.Minutes );
Console.WriteLine("Difference (hours)" + span.Hours );
Console.WriteLine("Difference (days)" + span.Days );

See similar question here Showing Difference between two datetime values in hours

Or you could work out the difference in the SQL query, I would need to know what type of database you are connecting to

MySQL

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

MSSQL

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Community
  • 1
  • 1
toby
  • 12
  • 5
0
           //Your Data table
            DataTable dt = new DataTable();
            //Let you have following columns
            dt.Columns.Add("Id");
            dt.Columns.Add("FromDate");
            dt.Columns.Add("ToDate");

       //Adding rows in data table
        dt.Rows.Add(1, "2017-06-27T13:58:39Z", "2017-04-27T13:58:39Z");
        dt.Rows.Add(2, "2017-07-27T13:58:39Z", "2017-03-27T13:58:39Z");
        dt.Rows.Add(3, "2017-08-27T13:58:39Z", "2017-03-27T13:58:39Z");
        dt.Rows.Add(4, "2017-09-27T13:58:39Z", "2017-03-27T13:58:39Z");
        dt.Rows.Add(5, "2017-10-27T13:58:39Z", "2017-03-27T13:58:39Z");



        string fromDate = string.Empty;
        string toDate = string.Empty;
        //Looping data to get fromdate and todate value from each row
        foreach (DataRow dr in dt.Rows)
        {
            fromDate = dr[1].ToString();
            toDate = dr[2].ToString();
            DateTime dtFromDate = Convert.ToDateTime(fromDate);
            DateTime dtToDate = Convert.ToDateTime(toDate);
            //Subtract startTimeDt from endTimeDt and get toatal seconds
            var diffInSeconds = (dtFromDate - dtToDate).TotalSeconds;

        }