How to get custom formatted date and time string in C
In Category C/C++
The C library function strftime() can be used to print date and time in string format. This function converts a broken-down date and time represented by struct tm according to the given format specification. The other library functions time() and localtime() can be used to get the time in broken-down format. The following example get the current time and converts in to a string format and prints it on the screen.
[neo@techpulp ~]# cat mytime.c
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[])
{
time_t t;
struct tm *tm;
char buf[255];
time(&t);
tm = localtime(&t);
strftime(buf, sizeof(buf), "%d %b %Y %H:%M", tm);
puts(buf);
return 0;
}
[neo@techpulp ~]#
Let us compile and execute the above program.
[neo@techpulp ~]# gcc mytime.c -o mytime [neo@techpulp ~]# ./mytime 10 Nov 2008 11:33 [neo@techpulp ~]#
Recent Comments