need "yy-ddd-hh:mm:ss ==> (time_t) clock" converter

mike at bria.UUCP mike at bria.UUCP
Sun Jan 20 08:49:28 AEST 1991


In article <TSINGLE.91Jan18120847 at sunland.gsfc.nasa.gov> sunland.gsfc.nasa.gov!tsingle (Tim Singletary) writes:
>Help!  I need something to convert yy-ddd-hh:mm:ss (i.e. year,
>day_of_year, hour, minute, second) to a unix-style
>_number_of_seconds_since_00:00:00_GMT,_Jan._1,_1970_.

I am doing this with the full knowledge that people are going to send me
flaming mail about what an ugly solution this is, but ... here is a little
ditty I wrote that seems to even work ...

/*	@(#)tmparse.c	1.1 	parse a time specification
*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#define ONE_DAY		86400L
#define ONE_YEAR	31564800L
#define ONE_THIRD	28800L

int mdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

main()
{
long	now;
char	buf[64];

	for (;;) {
		printf("Enter date: ");
		if ( gets(buf) == NULL )
			break;

		tmparse(buf,&now);
		printf("%s",ctime(&now));
		}
}

long tmparse(buf,when)
char	*buf;
long	*when;
{
long		date, now;
int		year = 1970, month = 0, day = 0;
int		hours = 0, mins = 0, secs = 0, count;
char		*ptr, *next;
struct tm	*lt;

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

	if ( strchr(buf,'/') == NULL && strchr(buf,'-') == NULL ) {
		month = lt->tm_mon;
		day = lt->tm_mday - 1;
		year = lt->tm_year + 1900;
		next = buf;
		}
	else {
		month = atoi(strtok(buf,"/-")) - 1;
		day = atoi(strtok(NULL,"/-")) - 1;
		year = atoi(strtok(NULL," "));
		next = NULL;

		if ( year == 0 )
			year = lt->tm_year + 1900;
		else if ( year < 100 )
			year += 1900;
		}

	if ( year < 1970 ) {
		*when = 0L;
		return(0L);
		}

	if ( (ptr = strtok(next,":")) != NULL ) {
		while ( isspace(*ptr) )
			++ptr;
		hours = atoi(ptr);
		mins = atoi(strtok(NULL,":"));
		secs = atoi(strtok(NULL,""));
		}

	date = 0L;
	for ( count = 1970; count < year; count++) {
		date += ONE_YEAR;
		if ( count % 4 == 0 || count % 400 == 0 )
			date += ONE_DAY;
		}
	date -= (year - 1971) * ONE_THIRD;

	for ( count = 0; count < month; count++) {
		date += mdays[count] * ONE_DAY;
		if ( count == 1 && (year % 4 == 0 || year % 400 == 0) )
			date += ONE_DAY;
		}

	date += (day * ONE_DAY) + secs + (mins * 60) + (hours * 3600);

	lt = localtime(&date);
	date += (hours - lt->tm_hour) * 3600;

	*when = date;
	return(date);
}
-- 
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
--
technoignorami (tek'no-ig'no-ram`i) a group of individuals that are constantly
found to be saying things like "Well, it works on my DOS machine ..."



More information about the Comp.unix.programmer mailing list