Commit | Line | Data |
---|---|---|
6e1fe29b BJ |
1 | #include <sys/types.h> |
2 | #include <time.h> | |
50953c5b | 3 | #include <stdio.h> |
6e1fe29b BJ |
4 | /* |
5 | * Convert a ctime(3) format string into a system format date. | |
6 | * Return the date thus calculated. | |
7 | * | |
8 | * Return -1 if the string is not in ctime format. | |
9 | */ | |
10 | ||
11 | /* | |
12 | * Offsets into the ctime string to various parts. | |
13 | */ | |
14 | ||
15 | #define E_MONTH 4 | |
16 | #define E_DAY 8 | |
17 | #define E_HOUR 11 | |
18 | #define E_MINUTE 14 | |
19 | #define E_SECOND 17 | |
20 | #define E_YEAR 20 | |
21 | ||
22 | time_t unctime(str) | |
23 | char *str; | |
24 | { | |
25 | struct tm then; | |
26 | char dbuf[30]; | |
27 | time_t emitl(); | |
28 | ||
29 | if (strlen(str) != 25) | |
30 | str[25] = 0; | |
31 | strcpy(dbuf, str); | |
32 | dbuf[E_MONTH+3] = 0; | |
50953c5b | 33 | if ( (then.tm_mon = lookup(&dbuf[E_MONTH])) < 0) { |
6e1fe29b | 34 | return(-1);; |
50953c5b | 35 | } |
6e1fe29b BJ |
36 | then.tm_mday = atoi(&dbuf[E_DAY]); |
37 | then.tm_hour = atoi(&dbuf[E_HOUR]); | |
38 | then.tm_min = atoi(&dbuf[E_MINUTE]); | |
39 | then.tm_sec = atoi(&dbuf[E_SECOND]); | |
40 | then.tm_year = atoi(&dbuf[E_YEAR]) - 1900; | |
41 | return(emitl(&then)); | |
42 | } | |
43 | ||
44 | static char months[] = | |
45 | "JanFebMarAprMayJunJulAugSepOctNovDec"; | |
46 | ||
47 | static | |
48 | lookup(str) | |
49 | char *str; | |
50 | { | |
51 | register char *cp, *cp2; | |
52 | ||
53 | for (cp = months, cp2 = str; *cp != 0; cp += 3) | |
54 | if (strncmp(cp, cp2, 3) == 0) | |
55 | return((cp-months) / 3); | |
56 | return(-1); | |
57 | } | |
58 | /* | |
59 | * Routine to convert a localtime(3) format date back into | |
60 | * a system format date. | |
61 | * | |
62 | * Use a binary search. | |
63 | */ | |
64 | ||
65 | struct tm *localtime(); | |
66 | ||
67 | time_t emitl(dp) | |
68 | struct tm *dp; | |
69 | { | |
70 | time_t conv; | |
71 | register int i, bit; | |
72 | struct tm dcopy; | |
73 | ||
74 | dcopy = *dp; | |
75 | dp = &dcopy; | |
76 | conv = 0; | |
50953c5b | 77 | for (i = 30; i >= 0; i--) { |
6e1fe29b BJ |
78 | bit = 1 << i; |
79 | conv |= bit; | |
80 | if (dcmp(localtime(&conv), dp) > 0) | |
81 | conv &= ~bit; | |
82 | } | |
83 | return(conv); | |
84 | } | |
85 | ||
86 | /* | |
87 | * Compare two localtime dates, return result. | |
88 | */ | |
89 | ||
90 | #define DECIDE(a) \ | |
91 | if (dp->a > dp2->a) \ | |
92 | return(1); \ | |
93 | if (dp->a < dp2->a) \ | |
94 | return(-1) | |
95 | ||
96 | static | |
97 | dcmp(dp, dp2) | |
98 | register struct tm *dp, *dp2; | |
99 | { | |
100 | ||
101 | DECIDE(tm_year); | |
102 | DECIDE(tm_mon); | |
103 | DECIDE(tm_mday); | |
104 | DECIDE(tm_hour); | |
105 | DECIDE(tm_min); | |
106 | DECIDE(tm_sec); | |
107 | return(0); | |
108 | } | |
de3d01d2 | 109 | static char *sccsid = "@(#)unctime.c 1.3 (Berkeley) 81/04/18"; |