tags:

views:

51

answers:

1

Hello, I need a TimeSpan that takes into account working hours. Let's say that if we configure the TimeSpan with an 8 hour day, two days should return 16 total hours instead of 48. Does anybody know of such a class?

Thanks.

Edit

I need the same functionality as timespan but with configurable day duration. Adding, subtracting,..., should work taking this into account. I tried to extend TimeSpan, but it's sealed. Maybe I should go for some extension methods to implement this as Oded suggested (or something similar).

+1  A: 

If you simply want to figure out each day as 8 hours, you can do this:

return TimeSpan.TotalHours / 3;

Update:

Now that you provided some more detail, I would suggest wrapping timespan with your own type - you can have an HoursInWorkingDay property in it which will allow you to configure the number of hours in a working day.

Have a constructor that takes a timespan and assign that to a private timespan that you can use for calculations:

public class WrappedTimeSpan
{
    private TimeSpan ts;
    private int hoursInDay = 8;

    public WrappedTimeSpan(TimeSpan origTS)
    {
        ts = origTs;
    }

    public WrappedTimeSpan(TimeSpan origTS, int hoursInDay) : this(origTs)
    {
        hoursInDay = hoursInDay;
    }

    public int HoursInDay { get;}

    public int WorkingHours { get { return ts.TotalHours / hoursInDay; }}
}

This can be extended to cater for any other requirements you have.

Oded
very short, easy and nice +1
cevik
I was looking for a more complete solution...
Carles
Did you take into account examples such as span between Monday 16:30 and Tuesday 9:30 (should yield 1 hour), Friday 9h and Monday 9h (8hrs), culture differences in Muslim world (where Friday is weekday instead of Sunday), buisness differences (not all jobs begin at 9h and/or end at 17h), and extra bits of info such as overtime and holidays?
Dialecticus
@Carles - if you want a more complete solution (whatever that means), please provide a more complete question with much more detail.
Oded
@Oded: I think the comment is fair even from the original question. Just dividing hours by 3 doesn't work ("2 days 3 hours" would come back as "17 hours" instead of as "19 hours," for example), and doesn't allow for any manipulation (again, if I add 3 hours to a timespan and *then* divide by 3, I've only added one hour to my original span).
Dan Puzey
@Dialecticus - a TimeSpan is simply a range of time, there is no calendar context to it. 8 hours are 8 hours whatever context your try to put them in.
Oded
@Carles - answer updated with possible solution.
Oded
Thanks, I'll try this as an starting point.
Carles