C/C++: Format Output of Local Time

Jul 28, 2015

It is a bit different to do format output of local time in C++ between Windows and Unix like systems.

Unix version:

time_t t = time(NULL);
tm* p = localtime(&t);
char filename[100] = {0};
sprintf(filename,"%d%02d%02d%02d%02d%02d.txt",p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);

Windows version:

time_t t = time(NULL);
tm p;
localtime_s(&p, &t);
char filename[100] = {0};
sprintf_s(filename, "%d%02d%02d%02d%02d%02d.txt", p.tm_year+1900,p.tm_mon+1,p.tm_mday,p.tm_hour,p.tm_min,p.tm_sec);

As you can see, the main difference is localtime_s in Win vs localtime in Unix (sprintf_s in the same way as well). The function localtime is considered unsafe by Windows so localtime_s is proposed to replace it (refer to MSDN). localtime_s(&p, &t) transforms an int number t, which is returned by function time() and represents how many seconds from 1970-01-01 00:00:00 +0000 (UTC) till now, to a structure p, which can be easily used for format output of time, as shown in the program above.

It seems C++ 11 introduces some new stuff to handle time issues. Maybe I will look into it some day if I have time.

Reference: http://sodino.com/2015/03/15/c-time/


Tags: C/C++

Comment by Github Issues

License (CC) BY-NC-SA | Subscribe RSS | Email fzheng@link.cuhk.edu.hk