2017-05-07 57 views
1

我有一個輸出日期的代碼,現在我想將它轉換爲char數組。如何將日期結構轉換爲char數組

我該如何正確使用?

#include <iomanip> 
#include <chrono> 

using namespace std; 
using chrono::system_clock; 


time_t tt = system_clock::to_time_t(system_clock::now()); 
struct tm * ptm = localtime(&tt); 

回答

2

對該任務使用sprintf函數。

char buff[100]; 
    if(ptm->tm_mon < 10){ 
      if(ptm->tm_mday < 10){ 
        sprintf(buff,"%u-0%u-0%u",(unsigned)ptm->tm_year,(unsigned)ptm->tm_mon,(unsigned)ptm->tm_mday); 
      }else{ 
        sprintf(buff,"%u-0%u%u",(unsigned)ptm->tm_year,(unsigned)ptm->tm_mon,(unsigned)ptm->tm_mday); 
      } 
    }else{ 
      if(ptm->tm_mday < 10){ 
        sprintf(buff,"%u-%u-0%u",(unsigned)ptm->tm_year,(unsigned)ptm->tm_mon,(unsigned)ptm->tm_mday); 
      }else{ 
        sprintf(buff,"%u-%u-%u",(unsigned)ptm->tm_year,(unsigned)ptm->tm_mon,(unsigned)ptm->tm_mday); 
      } 
    } 

其餘取決於所需的格式。

+0

謝謝,還有一件事,我該如何添加零到日期,所以它會輸出07.05.2017,現在它的輸出是5.7.2017 – Viktor

+0

@Viktor我更新了我的答案 – RoiHatam