Boost logo

Boost Users :

From: james.jones_at_[hidden]
Date: 2006-09-01 11:23:46


From: kingos_at_[hidden]
> Hi,
>
> I am hoping to use boost::date_time to do some date calculations. What I want to do is
> basically work out the number of days to a given date with various exclusions applied.
>
> eg.
>
> How many working days are there to christmas?
>
> using namespace boost::gregorian;
>
> int CalculateDaysToChristmas()
> {
> date_period someHoliday(date(2006, Dec, 01), date_duration(1));
>
> date today(2006, Sep, 1);
>
> date christmas(2006, Dec, 25);
>
> int days = 0;
> for (day_iterator i = today; i != christmas; ++i)
> {
> if (is_weekday(*i) && !someHoliday.contains(*i))
> ++days;
> }
>
> return days;
> }
>
> However, I can't find a simply way to work out is_weekday ...
> Secondly, is there some way to put every sunday in as a date_period?
> Thirdly, this doesn't seem very optimal ... is there a better way of doing this?

First off, is_weekday is pretty simple, something like:

bool is_weekday(const gregorian::date& d)
{
        return d.day_of_week != Saturday && d.day_of_week != Sunday;
}

Second, I don't understand your question about Sundays.

Third, you're right, it isn't very optimal. You'd be better off to note that weekdays in a period are equal to:

complete weeks in the period * 5 +
extra weekdays at the end of the period -
holidays in the period

Complete weeks in the period is easy to compute (days_between/7); the extra weekdays could be done via iterator (but guarantee to be <= 6 times through the loop) or via lookup table if you want really fast results. So this just leaves holidays in the period. It would be pretty easy to build a class which implemented a fast (constant-time) lookup for the # of holidays given a starting and ending date. Once you've got that, voila.

If you're looking for some really quick way to do this in Boost::DateTime, I don't think it's possible. Holidays aren't even localizable, since different businesses in the same locale can have different holiday schedules. It might be nice to include some sort of "date-exclusion" functionality in Boost that would implement the class I propose above, but I'm not sure this would be generally useful enough to bother with. Anyone else have an opinion on this?

-
James Jones Administrative Data Mgmt.
Webmaster 375 Raritan Center Pkwy, Suite A
Data Architect Edison, NJ 08837


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net