Boost logo

Boost :

Subject: [boost] Date_Time previous_weekday() returns the same day
From: Klaim - Joël Lamotte (mjklaim_at_[hidden])
Date: 2011-07-12 13:04:24


Hi,

We have a bug that seems to comes from boost::date_time::previous_weekday()
(probably next_weekday() too) usage in case we want to go from a weekday to
another same weekday:

#include <iostream>#include <boost/date_time.hpp>#include
<boost/date_time/gregorian/gregorian.hpp>

 int main()
{
        using namespace boost::gregorian;
        auto today = date( 2011, Jul, 12 );
        
        auto last_tuesday = boost::date_time::previous_weekday( today,
greg_weekday(boost::date_time::Tuesday) );

        std::cout << today << '\n';
        std::cout << last_tuesday;
        std::cin.ignore();

        return 0;
}

This example runs but return the same date twice instead of giving the
tuesday before the given date (that is already a tuesday).
Compiled with VS2010SP1 (boost 1.46.1) and GCC4.4(boost 1.44.0 - didn't see
the difference in the code)
What we first supposed was it will go to the tuesday of the previous week if
we already are tuesday.
It appears to not work this way.

Is it the wanted behaviour?
If it is, I suggest the documentation to be enhanced to warn the user about
the case when you provide a date that is the same provided weekday.

The code of boost::date_time::previous_weekday() (as far as I understand
it) suggests that it should go to the previous week's weekday instead of
returning the same day:

template<class date_type, class weekday_type>
  inline
  date_type previous_weekday(const date_type& d, const weekday_type& wd)
  {
    return d - days_before_weekday(d, wd);
  }

and then :

template<typename date_type, class weekday_type>
  inline
  typename date_type::duration_type days_before_weekday(const
date_type& d, const weekday_type& wd)
  {
    typedef typename date_type::duration_type duration_type;
    duration_type wks(0);
    duration_type dd(wd.as_number() - d.day_of_week().as_number()); // 1
    if(dd.days() > 0){ // 2
      wks = duration_type(7);
    }
    // we want a number of days, not an offset. The value returned must
    // be zero or larger.
    return (-dd + wks); // 3
  }

Correct me if I'm wrong : 2. checks if the generated day is the same weekday
than the provided one, right?
So if I'm correct, there might be a problem in 1 or 3?

Thanks for your time.

Joël Lamotte


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk