Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono add days to current date

Tags:

c++

c++11

chrono

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?

like image 904
cateof Avatar asked Feb 08 '17 13:02

cateof


3 Answers

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.

like image 160
Howard Hinnant Avatar answered Oct 06 '22 01:10

Howard Hinnant


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);
like image 31
Hatted Rooster Avatar answered Oct 06 '22 01:10

Hatted Rooster


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.

like image 25
eerorika Avatar answered Oct 05 '22 23:10

eerorika