2

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?

lubgr
  • 37,368
  • 3
  • 66
  • 117
Fuad
  • 75
  • 2
  • 6
  • 1
    A `std::tm` instance is not directly transferable to the `` type system. `tm` represents a calendar date and time, while `` operates with `std::chrono::time_point` instantiations, that don't know about days and that depend on a `clock` (template parameter). Maybe you can give us some more details about what you intend to do with the resulting object? – lubgr Oct 10 '19 at 08:29
  • I'm receiving a 24hr timestamp. I'd like to convert this to a chrono time. I assume using the ```system_clock::now()``` would reference the epoch time, giving me a date reference as well. Basically I would like to convert the 24hr timestamp to an epoch time. – Fuad Oct 10 '19 at 08:51
  • So the 24h timestamp is an integer denoting the number of seconds from the start of a day, reaching the end of that day at max? – lubgr Oct 10 '19 at 08:58
  • Yes that is correct – Fuad Oct 10 '19 at 09:15

3 Answers3

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 :)

Fuad
  • 75
  • 2
  • 6
0

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;
}
yumetodo
  • 1,147
  • 7
  • 19
0

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.

lubgr
  • 37,368
  • 3
  • 66
  • 117