time functions

Lars Wirzenius wirzeniu at klaava.Helsinki.FI
Wed Jun 12 22:26:32 AEST 1991


In article <6583 at graphite14.UUCP> johnsonl at motcid.UUCP (Lisa A. Johnson) writes:
>I'm trying to write a program that finds the local time using the
>functions in time.h.  I don't care about the date, I just want the
>time, but I can't figure out how to do it.  Can anyone out there
>help?  Which functions do I have to use, and what kind of variables
>do I need?

The first thing you need to know is that there are two ways to represent
the time in the standard C library. The first one uses a type called
type_t (often long, but don't count on it; however, you may have to use
long on some old Unix systems). This is a typedef for some integer type,
and holds the time encoded in some suitable way.

You can get the current date and time as a time_t object with the
function time, for example:

	time_t now;

	time(&now);

time_t alone is more or less useless, it cannot be used for nearly
anything. For further processing it needs to be converted to the other
kind of representation, a struct tm. The conversion is done with the
function localtime, for example:

	time_t now;
	struct tm *now_tm;

	time(&now);
	now_tm = localtime(&now);

A struct tm has (at least) the following fields:

	tm_year		year
	tm_mon		month
	tm_mday		day of the month
	tm_wday		day of the week
	tm_hour		hour of the day
	tm_min		minutes past full hour
	tm_sec		seconds past full minute

The last three are what you are searching for, I think.

Note that the localtime function returns a pointer to an internal struct
tm, and that the next call to localtime will overwrite this buffer. You
need to copy it to a safe place if you are going to need the data later.

There are also a number of other functions that may come in handy, these
include asctime, ctime, gmtime, and mktime. They should be covered in
any decent manual.
-- 
Lars Wirzenius     wirzeniu at cc.helsinki.fi



More information about the Comp.lang.c mailing list