xref: /original-bsd/sbin/dump/unctime.c (revision 52960f3f)
1 /*-
2  * Copyright (c) 1980, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)unctime.c	8.1 (Berkeley) 06/05/93";
10 #endif /* not lint */
11 
12 #include <sys/types.h>
13 
14 #include <stdio.h>
15 #include <time.h>
16 #ifdef __STDC__
17 #include <stdlib.h>
18 #include <string.h>
19 #endif
20 
21 #ifndef __P
22 #include <sys/cdefs.h>
23 #endif
24 
25 /*
26  * Convert a ctime(3) format string into a system format date.
27  * Return the date thus calculated.
28  *
29  * Return -1 if the string is not in ctime format.
30  */
31 
32 /*
33  * Offsets into the ctime string to various parts.
34  */
35 
36 #define	E_MONTH		4
37 #define	E_DAY		8
38 #define	E_HOUR		11
39 #define	E_MINUTE	14
40 #define	E_SECOND	17
41 #define	E_YEAR		20
42 
43 static	int dcmp __P((struct tm *, struct tm *));
44 static	time_t emitl __P((struct tm *));
45 static	int lookup __P((char *));
46 
47 
48 time_t
49 unctime(str)
50 	char *str;
51 {
52 	struct tm then;
53 	char dbuf[26];
54 
55 	(void) strncpy(dbuf, str, sizeof(dbuf) - 1);
56 	dbuf[sizeof(dbuf) - 1] = '\0';
57 	dbuf[E_MONTH+3] = '\0';
58 	if ((then.tm_mon = lookup(&dbuf[E_MONTH])) < 0)
59 		return (-1);
60 	then.tm_mday = atoi(&dbuf[E_DAY]);
61 	then.tm_hour = atoi(&dbuf[E_HOUR]);
62 	then.tm_min = atoi(&dbuf[E_MINUTE]);
63 	then.tm_sec = atoi(&dbuf[E_SECOND]);
64 	then.tm_year = atoi(&dbuf[E_YEAR]) - 1900;
65 	return(emitl(&then));
66 }
67 
68 static char months[] =
69 	"JanFebMarAprMayJunJulAugSepOctNovDec";
70 
71 static int
72 lookup(str)
73 	char *str;
74 {
75 	register char *cp, *cp2;
76 
77 	for (cp = months, cp2 = str; *cp != '\0'; cp += 3)
78 		if (strncmp(cp, cp2, 3) == 0)
79 			return((cp-months) / 3);
80 	return(-1);
81 }
82 /*
83  * Routine to convert a localtime(3) format date back into
84  * a system format date.
85  *
86  *	Use a binary search.
87  */
88 
89 static time_t
90 emitl(dp)
91 	struct tm *dp;
92 {
93 	time_t conv;
94 	register int i, bit;
95 	struct tm dcopy;
96 
97 	dcopy = *dp;
98 	dp = &dcopy;
99 	conv = 0;
100 	for (i = 30; i >= 0; i--) {
101 		bit = 1 << i;
102 		conv |= bit;
103 		if (dcmp(localtime(&conv), dp) > 0)
104 			conv &= ~bit;
105 	}
106 	return(conv);
107 }
108 
109 /*
110  * Compare two localtime dates, return result.
111  */
112 
113 #define DECIDE(a) \
114 	if (dp->a > dp2->a) \
115 		return(1); \
116 	if (dp->a < dp2->a) \
117 		return(-1)
118 
119 static int
120 dcmp(dp, dp2)
121 	register struct tm *dp, *dp2;
122 {
123 
124 	DECIDE(tm_year);
125 	DECIDE(tm_mon);
126 	DECIDE(tm_mday);
127 	DECIDE(tm_hour);
128 	DECIDE(tm_min);
129 	DECIDE(tm_sec);
130 	return(0);
131 }
132