问题
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?
回答1:
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, e.g.
#include <chrono>
const int timestamp = getSecondsSinceMidnight();
const std::chrono::seconds sec{timestamp};
Now you can proceed with that, e.g. subtract another timestamp etc.
回答2:
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 :)
回答3:
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;
}
来源:https://stackoverflow.com/questions/58318415/how-do-i-set-a-specific-time-using-the-stdchrono-library