如何将日期结构转换为char数组

时间:2017-05-07 14:15:41

标签: c++

我有一个输出日期的代码,现在我想将它转换为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);

1 个答案:

答案 0 :(得分: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);
            }
    }

其余的取决于所需的格式。