Saturday, January 17, 2009

gmtime and localtime (time.h)

We need to use structure for displaying local time (one time only). The program bellow uses predefined structure from “time.h”. The structure tm (which is defined in ) as follows:
#ifdef _TIME_H
__BEGIN_NAMESPACE_STD
/* Used by other time functions. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/

#ifdef __USE_BSD
long int tm_gmtoff; /* Seconds east of UTC. */
__const char *tm_zone; /* Timezone abbreviation. */
#else
long int __tm_gmtoff; /* Seconds east of UTC. */
__const char *__tm_zone; /* Timezone abbreviation. */
#endif
};

the structure can be read inside the manual for gcc library. Another declarations inside time.h that are interesting are :

__BEGIN_NAMESPACE_STD
/* Return the `struct tm' representation of *TIMER
in Universal Coordinated Time (aka Greenwich Mean Time). */
extern struct tm *gmtime (__const time_t *__timer) __THROW;

/* Return the `struct tm' representation
of *TIMER in the local timezone. */
extern struct tm *localtime (__const time_t *__timer) __THROW;

__END_NAMESPACE_STD

The program bellow uses gmtime(). According to gcc manual it is a functions that converts the calendar time timep (time protocol) to broken-down time representation, expressed in Coordinated Universal Time (UTC) or GMT.

#include "stdio.h"
#include "time.h"
int main()
{
time_t ttrs;
struct tm *ptrti;
time(&ttrs);
ptrti=gmtime(&ttrs);
printf("%d %d %d", ptrti->tm_hour, ptrti->tm_min, ptrti->tm_sec);
return 0;
}

The program above displays local time once. If you need to capture and display time once every second the you will need a loop. Inside this program we use localtime(). According to gcc manual, it is a function that converts the calendar time timep (time protocol) to broken time representation, expressed relative to the user’s specified time zone or local time zone.
#include "time.h"
#include "stdio.h"
int main()
{
int sh;
time_t rt;
struct tm * ti;
while(1)
{
time(&rt);
ti = localtime(&rt);
if (sh != ti->tm_sec) printf("%d %d %d\n", ti->tm_hour, ti->tm_min, ti->tm_sec);
sh = ti->tm_sec;
}
}