gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:44:34 24 4
gpt4 key购买 nike

我想根据月份输入计算从今天开始的过去日期。比如今天是 29-08-2019,6 个月前是 29-02-2019。

用户输入的是月数。可能是 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);

最佳答案

这很容易使用 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 格式获取当前日期就足够了,则不需要时区支持,您可以使用仅 header 库“date/date.h”(无需安装)。只需 #include "date/date.h" 而不是 #include "date/tz.h",并将前 3 行更改为:

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

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

关于c++ - 使用月份值计算过去的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57703539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com