C programming asctime time.h

In C programming the <time.h> asctime function break down the time pointed by the structure ‘tm’ to a string of 26 bytes containing the date and time in a timestamp format:

Sun Sep 16 01:03:52 1973\n\0

The Day ,Month date, hour, minute second and year.The declaration of the function is given below.

char *asctime(const struct tm *timeptr);

timeptr -The pointer to ‘struct tm’ type.

Return type
char* -Returns a pointer to the string.

This function’s sole purpose is to convert the time values stored by the ‘struct tm’ members to the said format string.It has no other purpose.A code example is given below.

Code example

time_t t;

time( &t ); //get the time of current moment

printf( “%s” , asctime( gmtime(&t) ) );


Thu Jul 20 16:13:54 2017

The function ‘gmtime’ convert the time stored in ‘t’ to Coordinated Universal Time(UTC, formerly known as Greenwich Mean Time);the time may not be same as the time shown in your computer.

Here we did not pass ‘struct tm’ object as argument to ‘asctime’ function instead we passed ‘time_t’ variable;that is also why we required calling ‘gmtime’ function before passing the argument to ‘asctime’.Note to get the local time:the time shown by your computer call the function ‘localtime’ instead of ‘gmtime’ function.

C time time.h

Note if the values are assigned directly to the ‘struct tm’ members you cannot call the ‘asctime’ function to get the string time format.In such case you must call ‘mktime’ function first to the ‘struct tm’ object and then call the ‘asctime’ function to get the string time format.A code example.

Code example

struct tm tt;

tt.tm_sec = 50;
tt.tm_min = 10;
tt.tm_hour = 3;
tt.tm_mday = 30;
tt.tm_mon = 5;
tt.tm_year = 100;
tt.tm_wday = 11;
tt.tm_yday = 111;
tt.tm_isdst = -1;

/*printf( “%s” , asctime(&tt) ); error */

mktime(&tt); //call this function first

printf( “%s” , asctime(&tt) ); //work fine!


Fri Jun 30 03:10:50 2000

Link : C mktime time.h

*Side Note

The ‘asctime’ function may be defined as,

char *asctime(const struct tm *timeptr)
static const char wday_name[7][3] = {
 “Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”};

static const char mon_name[12][3] = {
 “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”,
  “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec” };

static char result[26];

sprintf(result, “%.3s %.3s%3d %.2d:%.2d:%.2d %d\n” ,
 wday_name[timeptr->tm_wday] ,
 mon_name[timeptr->tm_mon] ,
 timeptr->tm_mday , timeptr->tm_hour ,
 timeptr->tm_min , timeptr->tm_sec ,
 1900 + timeptr->tm_year);

return result;

Related links

->C clock time.h

->C gmtime time.h

->C localtime time.h