Instead of using std::chrono::system_clock::now();
I would like to set my own specific hours\minutes\seconds. Similar to how one would go about using struct tm
to manually construct a date-time.
What is the best way of doing this?
I've found a solution I was looking for. See: A solution by Howard Hinnant
Basically you should use a 24hr duration
using days = std::chrono::duration<int, std::ratio<86400>>;
auto last_midnight = std::chrono::time_point_cast<days>(std::chrono::system_clock::now());
Then add the 24hr timestamp to it:)
You can use UDLs(User defined Literals) to create duration. Duration can be converted to timpoint via std::chrono::time_point
's constructor.
#include <iostream>
#include <chrono>
int main()
{
using namespace std::literals::chrono_literals;
auto nanoseconds_i = 3ns;
auto nanoseconds_f = 3.1ns;
std::cout << nanoseconds_i.count() << std::endl;
std::cout << nanoseconds_f.count() << std::endl;
}
Any clock provided by <chrono>
refers to an epoch, which is different from the point in time one your input delta refers to (based on the comments below the question). So you shouldn't try to use std::chrono::time_point
instances (the instantiations clocks deal with), but instead a std:chrono::duration
. The latter is agnostic of any reference point in time, as is your input. Depending on the unit of this input, pick one of the predefined std::duration
instantiations, eg
#include <chrono>
const int timestamp = getSecondsSinceMidnight();
const std::chrono::seconds sec{timestamp};
Now you can proceed with that, eg subtract another timestamp etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.