2017-09-14 3 views
2
time_t now = time(0); 
std::string h = std::string (ctime (&now)); 

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

Sortie courant que je reçois est: Thu Sep 14 10:58:26 2017Comment changer le format de la date et l'heure avec time_t?

Je veux la sortie comme 2017-08-26-16-10-56

Que puis-je faire pour que la production?

+1

connexes question: https: //stackoverflow.c om/questions/3673226/comment imprimer en temps-en-format-2009-08-10-181754-811 – rsp

Répondre

1

Utilisez strftime, comme ceci:

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

code complet:

#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; 
} 

Sortie:

2017-09-14-14-41-19

2

Utilisez 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; 

Sortie

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

Mieux encore, utilisez 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; 
}