我在我的项目中使用了HowardHinnant date库。我想在n个月之前得到确切的日期。查找n个月前的确切日期和时间?
例如:“2016-12-17 18:21:26”是当前日期时间,我想知道13个月前的日期时间。它应该输出“2015-11-17 18:21:26”。
/*
* This function will return the current date in year_month_day format
*/
auto currentDate() {
auto currentTime = std::chrono::system_clock::now();
date::year_month_day currentDate = date::floor<date::days>(currentTime);
return currentDate;
}
/*
* This function will find the date before (n) months
*/
template <typename T>
auto oldDate(T monthsNum) {
auto currentDate = currentDate();
auto yearCurrentDate = (int)currentDate.year();
auto monthCurrentDate = currentDate.month();
auto dayCurrentDate = currentDate.day();
auto yearNum = monthsNum/12;
auto yearEndDate = yearCurrentDate - yearNum;
auto monthNum = monthsNum%12;
auto monthEndDate = monthCurrentDate;
while(monthNum) {
monthEndDate--;
}
if(monthEndDate > monthCurrentDate) {
yearEndDate--;
}
date::year_month_day endDate = date::year{yearEndDate}/monthEndDate;
return endDate;
}
我的功能oldDate()
将返回这是n
个月之前的日期。但我无法获得时间。
如果没有这样的日期如'2016-03-31 18:21:26'前一个月? –
@ W.F。 :在这种情况下,它应该返回该月份和年份的最后日期。但是我的功能目前没有处理这种情况。 – Shravan40