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