开发者

Customize date format in C++

开发者 https://www.devze.com 2023-04-13 05:54 出处:网络
I have this function: void Log::Write(string logline){ //2011-10-12 13:07:40 correct format time_t rawtime;

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?


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;
}


Boost offers a library for that.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号