Getting the current time as a YYYY-MM-DD-HH-MM-SS string

左心房为你撑大大i 提交于 2019-11-29 11:12:59

问题


I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, but have a feeling that there's a nicer way to do this with date-time's formatting options. Is there such a way, and if so, how can I use it?


回答1:


Use std::strftime, it is standard C++.

#include <cstdio>
#include <ctime>

int main ()
{
    std::time_t rawtime;
    std::tm* timeinfo;
    char buffer [80];

    std::time(&rawtime);
    timeinfo = std::localtime(&rawtime);

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

    return 0;
}



回答2:


The answer depends on what you mean by get and take. If you are trying to output a formatted time string, use strftime(). If you are trying to parse a text string into a binary format, use strptime().



来源:https://stackoverflow.com/questions/5438482/getting-the-current-time-as-a-yyyy-mm-dd-hh-mm-ss-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!