Outputting date in ISO 8601 format

Documentation is your friend:

std::time_t t
    = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::put_time( std::localtime( &t ), "%FT%T%z" );

in my system yields

2016-04-29T02:48:56+0200

Based on @Uri's answer which fixes a few bugs and shows the time in the proper timezone along with the milliseconds in ISO8601 format:

auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
std::tm* now_tm = std::localtime(&time);
long long timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();

std::cout << std::setfill('0') 
          << std::put_time(now_tm, "%FT%H:%M:")
          << std::setw(2) << (timestamp / 1000) % 60 << '.'
          << std::setw(3) << timestamp % 1000
          << std::put_time(now_tm, "%z");

Tags:

C++