I have this code:
COleDateTime datStart = COleDateTime::GetCurrentTime(), datEnd;
// Update end date (one year later)
datEnd.SetDateTime(datStart.GetYear() + 1,
datStart.GetMonth(),
datStart.GetDay(),
datStart.GetHour(),
datStart.GetMinute(),
datStart.GetSecond());
The above code failed yesterday (Feb 29, 2020) because datEnd
resulted in Feb 29, 2021 which is not valid.
What is the right way to safely add a year to datStart
taking into account leap years?
C# has:
DateTime theDate = DateTime.Now;
DateTime yearInTheFuture = theDate.AddYears(1);
What is the equivalent for MFC/C++?
One possibility is:
COleDateTimeSpan spnYear;
spnYear.SetDateTimeSpan(365, 0, 0, 0);
datEnd = datStart + spnYear;
But it is still potentially flawed due to leap years having 366 days. So what is the right way?
I see this similar question:
It implies using boost
. I do have boost in my project although never used it for date manipulation. Wonder if this can be used with a COleDateTime
object?
Using boost
:
boost::gregorian::date dStart{ datStart.GetYear(), datStart.GetMonth(), datStart.GetDay() };
boost::gregorian::date dEnd = dStart + boost::gregorian::years(1);
datEnd.SetDateTime(
dEnd.year(),
dEnd.month(),
dEnd.day(),
datStart.GetMonth(),
datStart.GetMinute(),
datStart.GetSecond());
Doesn't compile.
4>D:\My Programs\2019\MeetSchedAssist\Meeting Schedule Assistant\PublishersDatabaseDlg.cpp(354,49): error C2398: Element '1': conversion from 'int' to 'boost::gregorian::date::year_type' requires a narrowing conversion
4>D:\My Programs\2019\MeetSchedAssist\Meeting Schedule Assistant\PublishersDatabaseDlg.cpp(354,70): error C2398: Element '2': conversion from 'int' to 'boost::gregorian::date::month_type' requires a narrowing conversion
4>D:\My Programs\2019\MeetSchedAssist\Meeting Schedule Assistant\PublishersDatabaseDlg.cpp(354,89): error C2398: Element '3': conversion from 'int' to 'boost::gregorian::date::day_type' requires a narrowing conversion