This is made much easier in C++20. In C++11, you can use Howard Hinnant's date/time library to start using the C++20 syntax today:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
cout << date::format("%m/%d/%Y %H:%M\n", chrono::system_clock::now());
}
This outputs your system time in your desired format. Your system keeps UTC time, not local time. This just output for me:
10/16/2018 13:32
If you don't need local time / time zone support, this is a single header, header-only library. Just include date/date.h
and you're good to go. If you need time zone support, there is an additional time zone library at the same link, but it is not header-only. It has one source tz.cpp
that must be compiled. It can be used like this:
#include "date/tz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
cout << date::format("%m/%d/%Y %H:%M\n",
date::make_zoned(date::current_zone(), chrono::system_clock::now()));
}
which for me changes the output to:
10/16/2018 09:32
This code (both examples) will port to C++20 by removing the #include "date/..."
, changing date::format
to chrono::format
, and changing date::make_zoned
to chrono::zoned_time
. If you have C++17, you can change date::make_zoned
to date::zoned_time
today (requires C++17 template deduction guides).