c++c++11stdc++-chronotime-t

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:


Solution

  • 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