The short version looks like this.
Adding a few comments...Code:#include <stdio.h> #include <time.h> int main(void) { time_t now; if ( time(&now) != (time_t)(-1) ) { struct tm *mytime = localtime(&now); if ( mytime ) { char buffer [ 32 ]; if ( strftime(buffer, sizeof buffer, "%X", mytime) ) { printf("buffer = \"%s\"\n", buffer); } } } return 0; } /* my output buffer = "09:09:26" */
Look up the format specifiers for strftime to customize the output, and adjust the buffer size as necessary.Code:#include <stdio.h> #include <time.h> int main(void) { time_t now; /* * The next line attempts to get the current time. * The result is stored in 'now'. * If the call to time() fails, it returns (time_t)(-1); verify success * before continuing on. */ if ( time(&now) != (time_t)(-1) ) { /* * Declare a variable 'mytime' and initialize it to a pointer to the * result of calling localtime(). * The localtime() function converts the calendar time in 'now' into a * broken-down time, expressed as local time. * This is needed for the call to strftime(). */ struct tm *mytime = localtime(&now); /* * If localtime() fails, it returns a null pointer; verify success before * continuing on. */ if ( mytime ) { char buffer [ 32 ]; /* * Use strftime() to create a string representation of the broken-down * time. * If strftime() fails, zero is returned and the contents of the array * are indeterminate; verify success before continuing on. */ if ( strftime(buffer, sizeof buffer, "%X", mytime) ) { /* * We were able to get the current time, we were able to convert * this value to local time and point to its structure, we were able * to create a string in our chosen format, so let's print it. * The double quotes help show the full contents of the string we * have created. */ printf("buffer = \"%s\"\n", buffer); } } } return 0; } /* my output buffer = "09:09:26" */


LinkBack URL
About LinkBacks





Reply With Quote








Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum