Customize date format in C++

风流意气都作罢 提交于 2019-12-08 00:10:24

问题


I have this function:

void Log::Write(string logline){
//2011-10-12 13:07:40 correct format
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    m_stream.write( asctime (timeinfo), 24 );
    m_stream << " - " << logline << std::endl;
}

The output is like this:

Thu Oct 13 12:35:30 2011

but I wanna see the output like the comment section:

2011-10-12 13:07:40

How is it possible?


回答1:


It's very possible. Look at the manpage for strftime(). In this case, you'd want:

void Log::Write(string line) 
{
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];

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

    strftime (buffer,80,"%Y-%m-%d %H:%M:%S",timeinfo);
    m_stream << buffer << " - " << line << endl;
}



回答2:


Boost offers a library for that.




回答3:


You can use the strftime() function to format times in all ways you want. In your case the format string "%Y-%m-%d %H:%M:%S" should produce the desired result.




回答4:


You can use strftime() to convert a struct tm into a string with somewhat flexible formatting.



来源:https://stackoverflow.com/questions/7753145/customize-date-format-in-c

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