我有一个输出日期的代码,现在我想将它转换为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);
答案 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);
}
}
其余的取决于所需的格式。