Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid going through time_t to print a time_point?

Here's an example adapted from cppreference.com :

#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>

int main() {
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::cout << "The time was just "
              << std::put_time(std::localtime(&now_c), "%F %T") << '\n';
}

I don't like this. I want to print my time point without having to go through time_t. Can I do so...:

  1. at all?
  2. with an arbitrary format like put_time supports?

Notes:

  • Standard library solutions are best; non-standard but robust solutions are also relevant.
  • Not a dupe of this - since I'm also interested in arbitrary format printing; but it should be noted that @HowardHinnant's answer to that one resolves the first part of this one.
like image 228
einpoklum Avatar asked Oct 18 '25 23:10

einpoklum


2 Answers

Howard Hinnant's library - which has been voted to become part of C++20 - also supports put_time-like formatting.

#include "date/date.h"
#include <iostream>

int
main()
{
    std::cout << date::format("%m/%d/%Y %I:%M:%S %p\n", std::chrono::system_clock::now());
}

Example output:

07/22/2018 03:30:35.001865 AM
like image 152
Howard Hinnant Avatar answered Oct 20 '25 11:10

Howard Hinnant


A partial solution which doesn't allow you a choice of printing format or timezone, thanks to @inf's suggestion, is found in this answer: you can simply pipe a timepoint to the standard output to get a UTC timestamp string for it:

std::cout << std::chrono::system_clock::now() << " UTC\n";

but the question remains open for arbitrary formats.

like image 39
einpoklum Avatar answered Oct 20 '25 12:10

einpoklum