[comp.lang.c] Date reading in C...

bwilliam%peruvian.utah.edu@cs.utah.edu (Bruce R. Williams) (02/04/91)

In article <1991Feb2.193758.7570@cs.dal.ca> dinn@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:

-Bruce

------------------
/* Retrieve and display the system date */
/* Written by Bruce R. Williams */

#include <stdio.h>
#include <dos.h>

main()
{
    struct date dt;
    char *month[] = {"January", "February", "March", "April", "May",
		    "June", "July", "August", "September", "October",
		    "November", "December"};

    getdate(&dt);
    printf("Today is %s %d, %d\n",month[dt.da_mon - 1],dt.da_day,dt.da_year);
}
Bruce R. Williams                "The most beautiful thing we can experience
University of Utah                is the mysterious.  It is the source of all
(bwilliam@peruvian.utah.edu)      true art and science."  -Albert Einstein

steve@taumet.com (Stephen Clamage) (02/05/91)

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

>In article <1991Feb2.193758.7570@cs.dal.ca> dinn@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@taumet.com