7

Simple question, how to properly convert std::chrono::time_point to a std::string with as little code as possible?

Notes: I don't want to use cout it with put_time(). C++11 and C++14 solutions are accepted.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
draganrakita
  • 188
  • 2
  • 8
  • 1
    Welcome to StackOverflow! Could you provide code representing Minimal, Complete, and Verifiable example of your task? See https://stackoverflow.com/help/mcve – David C. Jan 12 '18 at 00:14
  • Hi Davic C. glad to be here. I dont have code that i need to debug or task to finish, i want to find appropriate and elegant solution that i can use in future. – draganrakita Jan 12 '18 at 19:42

2 Answers2

6

Using only standard library headers (works with >= C++11):

    #include <ctime>
    #include <chrono>
    #include <string>
  
    using sc = std::chrono::system_clock ;
    std::time_t t = sc::to_time_t(sc::now());
    char buf[20];
    strftime(buf, 20, "%d.%m.%Y %H:%M:%S", localtime(&t));
    std::string s(buf);
StPiere
  • 4,113
  • 15
  • 24
5
#include "date/date.h"
#include <type_traits>

int
main()
{
    auto s = date::format("%F %T", std::chrono::system_clock::now());
    static_assert(std::is_same<decltype(s), std::string>, "");
}

date/date.h is found here. It is a header-only library, C++11/14/17. It has written documentation, and a video introduction.

Update:

In C++20 the syntax is:

#include <chrono>
#include <format>
#include <type_traits>

int
main()
{
    auto s = std::format("{:%F %T}", std::chrono::system_clock::now());
    static_assert(std::is_same_v<decltype(s), std::string>{});
}
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • Hi @Howard, Thank you for making date library it seems like great code and i will for sure dive into it (and probably use it), but for this question i want to find solution that uses standard libraries. – draganrakita Jan 12 '18 at 19:53
  • I understand, and good luck in your search. One such strategy is go on vacation for a few years and *maybe* when you come back, this *will* *be* part of the standard library. ;-) [Proposal](https://wg21.link/p0355) – Howard Hinnant Jan 12 '18 at 20:26
  • 1
    I hope it does, we need something like this. :) – draganrakita Jan 12 '18 at 23:28