Date reading in C...

Stephen Clamage steve at taumet.com
Tue Feb 5 03:39:08 AEST 1991


bwilliam%peruvian.utah.edu at cs.utah.edu (Bruce R. Williams) writes:

>In article <1991Feb2.193758.7570 at cs.dal.ca> dinn at ug.cs.dal.ca (Michael Dinn) writes:
>>I need some C code that will give me the variables month, day and year
>>as being set to the current month day and year. (time would be
>>nce as well as the date...)
>> Examples of any sort would be welcomed...

>This is a very system-specific question.  Here is an example using
>Turbo C 2.0 on an AT: ...

It need not be very system-specific.  Standard (ANSI/ISO) C provides for
a collection of functions which do what you want.  The only system-specific
feature is that an implementation need not provide the current date and
time -- but even then, Standard C allows you to find that out.

Standard header <time.h> provides the types "time_t" and "struct tm",
and the functions
	time_t time(time_t *);
	struct tm *localtime(const time_t *);

This is a portable solution (among Standard C implementations):

	#include <time.h>

	/* set mon, day, year, or return 0 if time not available */
	int get_date(int *mon, int *day, int* year)
	{
	    struct tm *t;
	    time_t timer = time((time_t*)0);
	    if( timer == (time_t)(-1) )
		return 0;		/* time not available */

	    t = localtime(timer);
	    *mon = t->tm_mon;		/* January == 0 */
	    *day = t->tm_mday;		/* 1-31 */
	    *year = t->tm_year;		/* 1900 == 0 */
	    return 1;			/* success */
	}
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list