std::chrono add days to current date

岁酱吖の 提交于 2020-05-29 05:28:43

问题


I would like to use std::chrono in order to find calculate the date in the future based on an expiration period.

The expiration period is an integer that specifies "days from now". So how do I use chrono lib in order to find the date after 100 days?


回答1:


Say you have a time_point. To add days to that object you can just use operator+ with std::chrono::hours :

#include <chrono>
std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
std::chrono::system_clock::time_point new_t = t + std::chrono::hours(100 * 24);



回答2:


Howard Hinnant's date library is free (open-source); it extends <chrono> with calendrical services:

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

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto now = system_clock::now();
    auto today = floor<days>(now);
    year_month_day future = today + days{100};
    std::cout << future << '\n';
}

The above program gets the current time with system_clock::now(), and then truncates that time_point to have a precision of days. Then 100 days are added to find the future time_point which is then converted into a {year, month, day} structure for human consumption.

The output is currently:

2017-05-19

If you want to do this type of computation without the benefit of a 3rd-party library, I highly recommend creating a chrono::duration days like so:

using days = std::chrono::duration
    <int, std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>>;

Now you can add days{100} to a system_clock::time_point.




回答3:


The chrono library contains no calendar functionality. There is no direct way to accurately achieve what you are asking for.

You can find a timestamp that is 100 days worth of seconds in future by using a duration with ratio of seconds per day. But chrono has no tools for calculating the date.



来源:https://stackoverflow.com/questions/42114518/stdchrono-add-days-to-current-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!