How do I set a specific time using the std::chrono library?

给你一囗甜甜゛ 提交于 2021-01-29 13:12:20

问题


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

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