Hello,
I come from a language where encoding date and time into variable was as simple as:
|
DateTime date_time = EncodeDateTime(2018, 1, 1, 23, 59, 59, 999); // pseudo code
|
I am struggling to do the same in C++. Was trying to find answer on the Internet but couldn't so far.
So far, I understand how to manipulate time_point, I know that I can add duration to it. However, to encode exact date, like the one in example, I would have to know number of days since epoch to 01/01/2018.
Knowing this I can do something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main()
{
std::chrono::time_point<std::chrono::system_clock> date_time;
std::time_t now_c = std::chrono::system_clock::to_time_t(date_time);
std::cout << "Time " << std::put_time(std::gmtime(&now_c), "%F %T") << '\n';
std::chrono::milliseconds milliseconds(999);
std::chrono::seconds seconds(59);
std::chrono::minutes minutes(59);
std::chrono::hours hours(17532 * 24 + 23);
date_time = date_time + hours + minutes + seconds + milliseconds;
now_c = std::chrono::system_clock::to_time_t(date_time);
std::cout << "Time " << std::put_time(std::gmtime(&now_c), "%F %T") << '\n';
}
|
So I guess, I could look on the Internet how to calculate number of days between two dates and derive my own EncodeDateTime routine, but I don't want to reinvent the wheel. Maybe there is already such function in standard library?
I also care about milliseconds and portability. This must work on every platform.
Thank you.