tags:

views:

80

answers:

5

Hello,

Does someone knows how to calculate the total hours between 2 times? For example if a worker clocks in at 8:00 and out at 16:00, I would like to know that in decimal it's 8.0 hours and it's 8:00 hours.

I'm using C# framework 2.0. The variables that hold the in and out time are of type string.

TY

A: 

You can do it by subtracting two datetimes and using the TotalHours property of the resulting Timespan. Heres an example:

    DateTime start = new DateTime(2010, 8, 25, 8, 0, 0);
    DateTime end = new DateTime(2010, 8, 25, 16, 0, 0);
    int hours = end.Subtract(start).TotalHours;
w69rdy
this is wrong. Hours return hour part of time, not total hours
Andrey
My bad, thanks for pointing it out
w69rdy
+7  A: 
        DateTime start = new DateTime(2010, 8, 25, 8, 0, 0);
        DateTime end = new DateTime(2010, 8, 25, 16, 0, 0);
        Console.WriteLine((end - start).TotalHours);

for strings:

        DateTime start = DateTime.Parse("8:00");
        DateTime end = DateTime.Parse("16:00");
        Console.WriteLine((end - start).TotalHours);
Andrey
+1 for using the subtraction operator overload; it's much more intuitive. It should be worth noting that the subtraction of two `DateTime`s will return a `TimeSpan`.
TheCloudlessSky
+1 only solution that is using strings. Well reading an answer completely and not just the title is a skill.
Yves M.
A: 
System.DateTime punchIn = new System.DateTime(2010, 8, 25, 8, 0, 0);

System.DateTime punchOut = new System.DateTime(2010, 8, 25, 16, 0, 0);

System.TimeSpan diffResult = punchOut.Subtract(punchIn);
PSU_Kardi
A: 

Check out TimeSpan.TotalHours:

TimeSpan difference = datetime2 - datetime1;
double totalHours = difference.TotalHours;
Justin Niessner
A: 

I came up with this daylight saving time safe method. The function is correct for both UTC and local timezones. If the DateTimeKind is Unspecified on either of the inputs then the return value is undefined (which is a fancy way of saying it could be incorrect).

private double TotalHours(DateTime earliest, DateTime latest)
{
    earliest = (earliest.Kind == DateTimeKind.Local) ? earliest.ToUniversalTime() : earliest;
    latest = (latest.Kind == DateTimeKind.Local) ? latest.ToUniversalTime() : latest;
    return (latest - earliest).TotalHours;
}
Brian Gideon