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

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

,我接收電流輸出爲:Thu Sep 14 10:58:26 2017如何用time_t更改日期和時間的格式?

我想要的輸出2017-08-26-16-10-56

我能做些什麼來該輸出?

+1

相關問題:https://stackoverflow.c OM /問題/ 3673226 /如何對打印時的格式,2009-08-10-181754-811 – rsp

回答

1

使用strftime,像這樣:

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

全碼:

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

輸出:

2017-09-14-14-41-19

2

使用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; 

輸出

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

更妙的是,使用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; 
}