My Tech notes: Display Date Time C-Function use-strftime()-function
Subscribe

Unix Documentation

Free Online Unix Training Materials

Lists many links to free Unix training materials.

Pointers and Arrays Materials

Pointers and Arrays materials Explained for C beginners

C FAQ and General Questions C Interview Questions

Powered By

Free XML Skins for Blogger

Powered by Blogger

Wednesday, October 15, 2008

Display Date Time C-Function use-strftime()-function

I was looking for a c function which prints date in format Equivalent to %Y-%m-%d (the ISO 8601 date format). And also want to display The time in a.m. or p.m. notation. As In the POSIX locale this is equivalent to HH:MM:SS pm or am. I got some C code like
curr_time = time( NULL );
strncpy( time_string, ( ctime( &curr_time ) ), MAX_TIME_LENGTH );
time_string[ strlen( time_string ) - 1 ] = 0;
printf("%s:-> ", time_string );
which uses time function and gives time output; put this output in some temp file then read it as desired. Looks complex, need simple solution ahaa..
I discovered strftime() function, which made my time display life easier, rather than previous complex approach. And believe me its just four lines of C code.
declare variables:
struct tm *ptr;
time_t ltime;
char *year,*local_time;

Initialize pointers
year=(char*)(malloc(sizeof(char)));
local_time=(char*)malloc(sizeof(char));
Here we go
ltime = time(NULL); /* get current calendar time */
ptr = localtime(&ltime);
strftime(year,30,"%Y/%m/%d",ptr);
strftime(local_time,30,"%r",ptr);
printf("%s\n %s",year,local_time);

dig more about strftime - format date and time
#include

size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);

DESCRIPTION
The strftime() function formats the broken-down time tm according to
the format specification format and places the result in the character
array s of size max.
There are many good options which makes your time display requirement easier.

No comments:

Post a Comment