6
time_t now = time(0);  
std::string h = std::string (ctime (&now));

std::cout << "\nh: " << h;

Current output that I am receiving is: Thu Sep 14 10:58:26 2017

I want the output as 2017-08-26-16-10-56

What can I do to that output?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • 1
    Related question : https://stackoverflow.com/questions/3673226/how-to-print-time-in-format-2009-08-10-181754-811 – msc Sep 14 '17 at 05:37

2 Answers2

7

Use strftime, like this:

strftime (buffer, 80,"%Y-%m-%d-%H-%M-%S",timeinfo);

Full code:

#include <cstdio>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer [80];

  time (&rawtime);
  timeinfo = localtime (&rawtime);

  strftime (buffer, 80,"%Y-%m-%d-%H-%M-%S",timeinfo);
  puts (buffer);

  return 0;
}

Output:

2017-09-14-14-41-19

gsamaras
  • 71,951
  • 46
  • 188
  • 305
4

Use std::put_time

#include <iomanip>

time_t now = time(0);
std::string h = std::put_time(localtime(&now), "%F-%H-%M-%S");
std::cout << "\nh: " << h;

Output

h: 2017-09-14-05-54-02

Even better, use std::chrono

#include <iostream>
#include <iomanip>
#include <chrono>
using namespace std;

int main() {
    auto now = chrono::system_clock::to_time_t(chrono::system_clock::now());
    cout << put_time(localtime(&now), "%F-%H-%M-%S") << endl;
    return 0;
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50