I'm trying to handle dates and times in my code, and have been pointed in the direction of the boost library - specifically, boost::locale::date_time (in part because this lets me avoid Daylight Saving Time weirdness that was making my previous implementation difficult).
However, I'm getting inconsistent results. When I store a date in the date_time object and later try to get data from it, it is incorrect. Here's an example:
#include <boost\\asio\\error.hpp>
#include <boost\\locale.hpp>
using namespace std;
int main()
{
// Necessary to avoid bad_cast exception - system default should be fine
boost::locale::generator gen;
std::locale::global(gen(""));
// Create date_time of 12/19/2016
boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(12) + boost::locale::period::day(19);
unsigned int month = dt.get(boost::locale::period::month());
unsigned int day = dt.get(boost::locale::period::day());
unsigned int year = dt.get(boost::locale::period::year());
cout << month << "/" << day << "/" << year << endl;
// Expected output: 12/19/2016
// Actual output: 0/19/2017
}
What am I doing wrong? I just want to extract the saved days, months, years, hours, etc.
Thank you.
EDIT: It's possible I'm initially setting the date_time in an incorrect manner. Is there a better way to explicitly set a date time (for instance, to 12-19-2016), assuming I have all the relevant data in integer (not string) format?
2016-04-05
+ 12 months
= 2017-04-05
. This makes sense, since 12 months is a whole year.
Try adding 11 months instead, then increment to adjust from a 0-based month to a 1-based month.
boost::locale::date_time dt = boost::locale::period::year(2016) + boost::locale::period::month(11) + boost::locale::period::day(19);
uint month = dt.get(boost::locale::period::month()) + 1;
uint day = dt.get(boost::locale::period::day());
uint year = dt.get(boost::locale::period::year());
cout << month << "/" << day << "/" << year << endl;