Programming Tips - C/C++: How to quickly make a nice timestamp string

Date: 2010jan19 Update: 2026sep25 Language: C/C++ OS: Linux Level: novice Q. C/C++: How to quickly make a nice timestamp string A. Here's a function that does that:
// eg "Wed Jun 30 21:49:08 2026" void timeStamp(char *szTime, const size_t size) { szTime[0] = '\0'; if (size < 25) return; const time_t now = time(NULL); ctime_r(&now, szTime); szTime[24] = '\0'; // Zap the newline }
Full Example:
#include <time.h> #include <stdio.h> // (Place the above function here) int main() { char szTime[100]; timeStamp(szTime, sizeof(szTime)); printf("It is now %s\n", szTime); }
Output (at one time):
It is now Fri Sep 25 10:43:40 2026
The above works in Windows but here's the Windows-specific way: https://www.davekb.com/browse_programming_tips:cpp_windows_timestamp:txt