Link to home
Start Free TrialLog in
Avatar of devo00
devo00Flag for United States of America

asked on

Find # of hours between 2 dates, excluding weekends, in C#

I need to calculate the number of hours a ticket has been, or was open by subtracting 2 dates. All weekend hours need to be excluded. (All in C#) Can someone assist?
Avatar of jazzIIIlove
jazzIIIlove
Flag of Sweden image

Hi there;

yes we can...any code snippet you can provide us?

Best regards...
or algorithm?
Avatar of devo00

ASKER

Sure, so far I only display the flat difference in hours (see snippet). I need to adapt it to exclude weekends.

snippet.txt
Super quick, super dirty.  This calculates days but you could easily modify it to do hours.
I can modify it if you need.
            //Todays Date
            DateTime dt2 = DateTime.Now;
 
            //Previous Date
            DateTime dt = DateTime.Parse("10/15/2008");
 
            //TimeSpan Between Dates
            TimeSpan dt3 = dt2 - dt;
 
            //Count of days not including weekends
            int dayCount = 0;
 
            //1 day timespan
            TimeSpan ts = new TimeSpan(1, 0, 0, 0);
 
            for (int i = 1; i < dt3.Days+1; i++)
            {
                //Today - TimeSpan(1 Day)
                dt2 = dt2.Subtract(ts);
 
                if (dt2.DayOfWeek != DayOfWeek.Saturday && dt2.DayOfWeek != DayOfWeek.Sunday)
                {
                    dayCount++;
                }
               
            }

Open in new window

Avatar of devo00

ASKER

Yeah I definitely need hours, as in, if someone starts a ticket on Friday and happens to close it on a Saturday, none of the hours from Saturday count, and only the partial day (in hours) for Friday will count.
I'm not seeing a straight-forward way to do this above, would we convert the day count to a decimal and multiply by 24 at the end?
ASKER CERTIFIED SOLUTION
Avatar of nullcory
nullcory
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of devo00

ASKER

Excellent, thank you!  It seems to work for every test I've done so far.