使用月份值计算过去的日期

时间:2019-08-29 05:29:43

标签: c++ datetime

我想根据“月份”输入计算从今天开始的过去日期。 就像今天是2019年2月29日,比它是2019年2月29日早了6个月。

用户输入将是月数。可能是6、8、18、30、60 ... 我想计算确切的完成日期。我尝试使用下面的代码来帮助获取当前和过去一年的日期,但是我正在寻找一些解决方案来获取月份值更高的日期。

time_t now = time( NULL);
struct tm now_tm = *localtime( &now);


int inDuration = 0;
std::cout << "Add Duration..." << std::endl;
std::cin >> inDuration; //month value. looking for solution when mnth value is more then month in current and previous year.


int crnMonth = now_tm.tm_mon+1;
int pastDay = now_tm.tm_mday;
int pastMonth = 0;
int pastYear = now_tm.tm_year + 1900;


if(inDuration > crnMonth)
{
    pastMonth = (12-(inDuration-crnMonth));
    pastYear = (now_tm.tm_year + 1900)-1;
}
else
{
    pastMonth = crnMonth-inDuration;
}

printf("%d-%d-%d", pastDay, pastMonth, pastYear);

1 个答案:

答案 0 :(得分:1)

使用Howard Hinnant's free, open-source date/time library非常简单:

#include "date/tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;

    // Get current local date
    auto now_utc = floor<seconds>(system_clock::now());
    auto now_local = zoned_seconds{current_zone(), now_utc}.get_local_time();
    year_month_day crnDate{floor<days>(now_local)};

    // Get number of months
    int inDuration = 0;
    std::cout << "Add Duration..." << std::endl;
    std::cin >> inDuration;

    // Compute past date
    auto pastDate = crnDate - months{inDuration};
    if (!pastDate.ok())
        pastDate = pastDate.year()/pastDate.month()/last;
    std::cout << pastDate << '\n';
}

示例输出:

35
2016-09-29

前几行获取当前时间(以UTC为单位),然后将其转换为您的本地时间,然后将本地时间转换为{year, month, day}结构。

然后按照您的问题从用户获得所需的月数。

最后,将输入转换为months持续时间,并从当前日期中减去该持续时间。如果当前日期接近一个月末,则过去的日期可能不是有效日期(例如9月31日)。如果发生这种情况,则必须决定要做什么的政策。上面的示例选择“快照”到月底。其他政策,例如下个月溢出也可以。

有些installation is required for the local time zone support

如果在UTC中获取当前日期足够好,则不需要时区支持,您可以使用仅标头的库“ date / date.h”(无需安装)。只需#include "date/date.h"而不是#include "date/tz.h",然后将前三行更改为:

// Get current UTC date
year_month_day crnDate{floor<days>(system_clock::now())};

程序的其余部分使用相同的代码。