how to count total hours from c# datagridview

hamed algazaly 106 Reputation points
2021-11-01T23:43:44.79+00:00

145579-rowhours.jpg

hello everyone..

i calculate workers working hours by there login and logout time
as showing in this datagridview ..
how i can calculate they working hours from this datagridview
using for loop..

please help..

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2021-11-01T23:50:17.44+00:00

    You can use the Substract() method.

    For example
    DateTime date1 = Convert.ToDatetime("00:00:00");
    DateTime date2 = Convert.ToDatetime("00:00:00");

    double hours = 0;
    foreach (DataGridViewRow row in _grid.Rows)
    {
    date1 = (date)row.Cells[2].Value; // This one takes the first hour value
    date2 =(date)row.Cells[3].Value; // This one takes the second hour value
    hours += date2.Subtract(date1).TotalHours;
    }


1 additional answer

Sort by: Most helpful
  1. ShuaiHua Du 636 Reputation points
    2021-11-04T13:44:48.483+00:00

    Assume the model mapping to your database table is called "WorkTime" as below:

    public class WorkTime  
    {  
         public int Id { get; set; }  
         public DateTime StartTime { get; set; }  
         public DateTime EndTime { get; set; }  
    }  
      
    

    Let's extend it :

    public class WorkTime  
    {  
        public int Id { get; set; }  
        public DateTime StartTime { get; set; }  
        public DateTime EndTime { get; set; }  
        public TimeSpan WorkTimeSpan => EndTime - StartTime;  
        public string Days => string.Format("{0:%d}", WorkTimeSpan);  
        public string Hours => string.Format("{0:%h}", WorkTimeSpan);  
        public string Minutes => string.Format("{0:%m}", WorkTimeSpan);  
        public string Seconds => string.Format("{0:%s}", WorkTimeSpan);  
    }  
    

    Test it:

    [TestMethod]  
    public void Test_WorkTime()  
    {  
        var workTime = new WorkTime  
        {  
            Id = 1,  
            StartTime = new DateTime(2021, 11, 3, 21, 23, 33),  
            EndTime = DateTime.Now  
        };  
        Console.WriteLine($"{workTime.Days} days,{workTime.Hours} hours,{workTime.Minutes} minutes,{workTime.Seconds} seconds.");  
    
        //The output :   1 days,0 hours,12 minutes,46 seconds.  
    }  
    

    Now you can binding the "Days","Hours","Minutes","Seconds" to your DataGridView.

    If you calculate the total, you can subtract the minimum start time from the maximum end time , then get the TimeSpan.

    Enjoy Programing!!!

    Please refer to TimeSpan : TimeSpan

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.