]> granicus.if.org Git - postgresql/blob - src/interfaces/ecpg/pgtypeslib/dt_common.c
- Added Dave patch for Informix handling of numeric/int conversion.
[postgresql] / src / interfaces / ecpg / pgtypeslib / dt_common.c
1 #include "postgres_fe.h"
2
3 #include <time.h>
4 #include <ctype.h>
5 #include <math.h>
6
7 #include "extern.h"
8 #include "dt.h"
9 #include "pgtypes_timestamp.h"
10
11 static int      day_tab[2][13] = {
12         {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
13 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}};
14
15 typedef long AbsoluteTime;
16
17 #define ABS_SIGNBIT                             ((char) 0200)
18 #define POS(n)                                  (n)
19 #define NEG(n)                                  ((n)|ABS_SIGNBIT)
20 #define FROMVAL(tp)                             (-SIGNEDCHAR((tp)->value) * 15) /* uncompress */
21 #define VALMASK                                 ((char) 0177)
22 #define SIGNEDCHAR(c)   ((c)&ABS_SIGNBIT? -((c)&VALMASK): (c))
23
24 static datetkn datetktbl[] = {
25 /*      text, token, lexval */
26         {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
27         {"abstime", IGNORE_DTF, 0}, /* for pre-v6.1 "Invalid Abstime" */
28         {"acsst", DTZ, POS(42)},        /* Cent. Australia */
29         {"acst", DTZ, NEG(16)},         /* Atlantic/Porto Acre */
30         {"act", TZ, NEG(20)},           /* Atlantic/Porto Acre */
31         {DA_D, ADBC, AD},                       /* "ad" for years >= 0 */
32         {"adt", DTZ, NEG(12)},          /* Atlantic Daylight Time */
33         {"aesst", DTZ, POS(44)},        /* E. Australia */
34         {"aest", TZ, POS(40)},          /* Australia Eastern Std Time */
35         {"aft", TZ, POS(18)},           /* Kabul */
36         {"ahst", TZ, NEG(40)},          /* Alaska-Hawaii Std Time */
37         {"akdt", DTZ, NEG(32)},         /* Alaska Daylight Time */
38         {"akst", DTZ, NEG(36)},         /* Alaska Standard Time */
39         {"allballs", RESERV, DTK_ZULU},         /* 00:00:00 */
40         {"almst", TZ, POS(28)},         /* Almaty Savings Time */
41         {"almt", TZ, POS(24)},          /* Almaty Time */
42         {"am", AMPM, AM},
43         {"amst", DTZ, POS(20)},         /* Armenia Summer Time (Yerevan) */
44 #if 0
45         {"amst", DTZ, NEG(12)},         /* Porto Velho */
46 #endif
47         {"amt", TZ, POS(16)},           /* Armenia Time (Yerevan) */
48         {"anast", DTZ, POS(52)},        /* Anadyr Summer Time (Russia) */
49         {"anat", TZ, POS(48)},          /* Anadyr Time (Russia) */
50         {"apr", MONTH, 4},
51         {"april", MONTH, 4},
52 #if 0
53         aqtst
54         aqtt
55         arst
56 #endif
57         {"art", TZ, NEG(12)},           /* Argentina Time */
58 #if 0
59         ashst
60         ast                                                     /* Atlantic Standard Time, Arabia Standard
61                                                                  * Time, Acre Standard Time */
62 #endif
63         {"ast", TZ, NEG(16)},           /* Atlantic Std Time (Canada) */
64         {"at", IGNORE_DTF, 0},          /* "at" (throwaway) */
65         {"aug", MONTH, 8},
66         {"august", MONTH, 8},
67         {"awsst", DTZ, POS(36)},        /* W. Australia */
68         {"awst", TZ, POS(32)},          /* W. Australia */
69         {"awt", DTZ, NEG(12)},
70         {"azost", DTZ, POS(0)},         /* Azores Summer Time */
71         {"azot", TZ, NEG(4)},           /* Azores Time */
72         {"azst", DTZ, POS(20)},         /* Azerbaijan Summer Time */
73         {"azt", TZ, POS(16)},           /* Azerbaijan Time */
74         {DB_C, ADBC, BC},                       /* "bc" for years < 0 */
75         {"bdst", TZ, POS(8)},           /* British Double Summer Time */
76         {"bdt", TZ, POS(24)},           /* Dacca */
77         {"bnt", TZ, POS(32)},           /* Brunei Darussalam Time */
78         {"bort", TZ, POS(32)},          /* Borneo Time (Indonesia) */
79 #if 0
80         bortst
81         bost
82 #endif
83         {"bot", TZ, NEG(16)},           /* Bolivia Time */
84         {"bra", TZ, NEG(12)},           /* Brazil Time */
85 #if 0
86         brst
87         brt
88 #endif
89         {"bst", DTZ, POS(4)},           /* British Summer Time */
90 #if 0
91         {"bst", TZ, NEG(12)},           /* Brazil Standard Time */
92         {"bst", DTZ, NEG(44)},          /* Bering Summer Time */
93 #endif
94         {"bt", TZ, POS(12)},            /* Baghdad Time */
95         {"btt", TZ, POS(24)},           /* Bhutan Time */
96         {"cadt", DTZ, POS(42)},         /* Central Australian DST */
97         {"cast", TZ, POS(38)},          /* Central Australian ST */
98         {"cat", TZ, NEG(40)},           /* Central Alaska Time */
99         {"cct", TZ, POS(32)},           /* China Coast Time */
100 #if 0
101         {"cct", TZ, POS(26)},           /* Indian Cocos (Island) Time */
102 #endif
103         {"cdt", DTZ, NEG(20)},          /* Central Daylight Time */
104         {"cest", DTZ, POS(8)},          /* Central European Dayl.Time */
105         {"cet", TZ, POS(4)},            /* Central European Time */
106         {"cetdst", DTZ, POS(8)},        /* Central European Dayl.Time */
107         {"chadt", DTZ, POS(55)},        /* Chatham Island Daylight Time (13:45) */
108         {"chast", TZ, POS(51)},         /* Chatham Island Time (12:45) */
109 #if 0
110         ckhst
111 #endif
112         {"ckt", TZ, POS(48)},           /* Cook Islands Time */
113         {"clst", DTZ, NEG(12)},         /* Chile Summer Time */
114         {"clt", TZ, NEG(16)},           /* Chile Time */
115 #if 0
116         cost
117 #endif
118         {"cot", TZ, NEG(20)},           /* Columbia Time */
119         {"cst", TZ, NEG(24)},           /* Central Standard Time */
120         {DCURRENT, RESERV, DTK_CURRENT},        /* "current" is always now */
121 #if 0
122         cvst
123 #endif
124         {"cvt", TZ, POS(28)},           /* Christmas Island Time (Indian Ocean) */
125         {"cxt", TZ, POS(28)},           /* Christmas Island Time (Indian Ocean) */
126         {"d", UNITS, DTK_DAY},          /* "day of month" for ISO input */
127         {"davt", TZ, POS(28)},          /* Davis Time (Antarctica) */
128         {"ddut", TZ, POS(40)},          /* Dumont-d'Urville Time (Antarctica) */
129         {"dec", MONTH, 12},
130         {"december", MONTH, 12},
131         {"dnt", TZ, POS(4)},            /* Dansk Normal Tid */
132         {"dow", RESERV, DTK_DOW},       /* day of week */
133         {"doy", RESERV, DTK_DOY},       /* day of year */
134         {"dst", DTZMOD, 6},
135 #if 0
136         {"dusst", DTZ, POS(24)},        /* Dushanbe Summer Time */
137 #endif
138         {"easst", DTZ, NEG(20)},        /* Easter Island Summer Time */
139         {"east", TZ, NEG(24)},          /* Easter Island Time */
140         {"eat", TZ, POS(12)},           /* East Africa Time */
141 #if 0
142         {"east", DTZ, POS(16)},         /* Indian Antananarivo Savings Time */
143         {"eat", TZ, POS(12)},           /* Indian Antananarivo Time */
144         {"ect", TZ, NEG(16)},           /* Eastern Caribbean Time */
145         {"ect", TZ, NEG(20)},           /* Ecuador Time */
146 #endif
147         {"edt", DTZ, NEG(16)},          /* Eastern Daylight Time */
148         {"eest", DTZ, POS(12)},         /* Eastern Europe Summer Time */
149         {"eet", TZ, POS(8)},            /* East. Europe, USSR Zone 1 */
150         {"eetdst", DTZ, POS(12)},       /* Eastern Europe Daylight Time */
151         {"egst", DTZ, POS(0)},          /* East Greenland Summer Time */
152         {"egt", TZ, NEG(4)},            /* East Greenland Time */
153 #if 0
154         ehdt
155 #endif
156         {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
157         {"est", TZ, NEG(20)},           /* Eastern Standard Time */
158         {"feb", MONTH, 2},
159         {"february", MONTH, 2},
160         {"fjst", DTZ, NEG(52)},         /* Fiji Summer Time (13 hour offset!) */
161         {"fjt", TZ, NEG(48)},           /* Fiji Time */
162         {"fkst", DTZ, NEG(12)},         /* Falkland Islands Summer Time */
163         {"fkt", TZ, NEG(8)},            /* Falkland Islands Time */
164 #if 0
165         fnst
166         fnt
167 #endif
168         {"fri", DOW, 5},
169         {"friday", DOW, 5},
170         {"fst", TZ, POS(4)},            /* French Summer Time */
171         {"fwt", DTZ, POS(8)},           /* French Winter Time  */
172         {"galt", TZ, NEG(24)},          /* Galapagos Time */
173         {"gamt", TZ, NEG(36)},          /* Gambier Time */
174         {"gest", DTZ, POS(20)},         /* Georgia Summer Time */
175         {"get", TZ, POS(16)},           /* Georgia Time */
176         {"gft", TZ, NEG(12)},           /* French Guiana Time */
177 #if 0
178         ghst
179 #endif
180         {"gilt", TZ, POS(48)},          /* Gilbert Islands Time */
181         {"gmt", TZ, POS(0)},            /* Greenwish Mean Time */
182         {"gst", TZ, POS(40)},           /* Guam Std Time, USSR Zone 9 */
183         {"gyt", TZ, NEG(16)},           /* Guyana Time */
184         {"h", UNITS, DTK_HOUR},         /* "hour" */
185 #if 0
186         hadt
187         hast
188 #endif
189         {"hdt", DTZ, NEG(36)},          /* Hawaii/Alaska Daylight Time */
190 #if 0
191         hkst
192 #endif
193         {"hkt", TZ, POS(32)},           /* Hong Kong Time */
194 #if 0
195         {"hmt", TZ, POS(12)},           /* Hellas ? ? */
196         hovst
197         hovt
198 #endif
199         {"hst", TZ, NEG(40)},           /* Hawaii Std Time */
200 #if 0
201         hwt
202 #endif
203         {"ict", TZ, POS(28)},           /* Indochina Time */
204         {"idle", TZ, POS(48)},          /* Intl. Date Line, East */
205         {"idlw", TZ, NEG(48)},          /* Intl. Date Line, West */
206 #if 0
207         idt                                                     /* Israeli, Iran, Indian Daylight Time */
208 #endif
209         {LATE, RESERV, DTK_LATE},       /* "infinity" reserved for "late time" */
210         {INVALID, RESERV, DTK_INVALID},         /* "invalid" reserved for bad time */
211         {"iot", TZ, POS(20)},           /* Indian Chagos Time */
212         {"irkst", DTZ, POS(36)},        /* Irkutsk Summer Time */
213         {"irkt", TZ, POS(32)},          /* Irkutsk Time */
214         {"irt", TZ, POS(14)},           /* Iran Time */
215 #if 0
216         isst
217 #endif
218         {"ist", TZ, POS(8)},            /* Israel */
219         {"it", TZ, POS(14)},            /* Iran Time */
220         {"j", UNITS, DTK_JULIAN},
221         {"jan", MONTH, 1},
222         {"january", MONTH, 1},
223         {"javt", TZ, POS(28)},          /* Java Time (07:00? see JT) */
224         {"jayt", TZ, POS(36)},          /* Jayapura Time (Indonesia) */
225         {"jd", UNITS, DTK_JULIAN},
226         {"jst", TZ, POS(36)},           /* Japan Std Time,USSR Zone 8 */
227         {"jt", TZ, POS(30)},            /* Java Time (07:30? see JAVT) */
228         {"jul", MONTH, 7},
229         {"julian", UNITS, DTK_JULIAN},
230         {"july", MONTH, 7},
231         {"jun", MONTH, 6},
232         {"june", MONTH, 6},
233         {"kdt", DTZ, POS(40)},          /* Korea Daylight Time */
234         {"kgst", DTZ, POS(24)},         /* Kyrgyzstan Summer Time */
235         {"kgt", TZ, POS(20)},           /* Kyrgyzstan Time */
236         {"kost", TZ, POS(48)},          /* Kosrae Time */
237         {"krast", DTZ, POS(28)},        /* Krasnoyarsk Summer Time */
238         {"krat", TZ, POS(32)},          /* Krasnoyarsk Standard Time */
239         {"kst", TZ, POS(36)},           /* Korea Standard Time */
240         {"lhdt", DTZ, POS(44)},         /* Lord Howe Daylight Time, Australia */
241         {"lhst", TZ, POS(42)},          /* Lord Howe Standard Time, Australia */
242         {"ligt", TZ, POS(40)},          /* From Melbourne, Australia */
243         {"lint", TZ, POS(56)},          /* Line Islands Time (Kiribati; +14
244                                                                  * hours!) */
245         {"lkt", TZ, POS(24)},           /* Lanka Time */
246         {"m", UNITS, DTK_MONTH},        /* "month" for ISO input */
247         {"magst", DTZ, POS(48)},        /* Magadan Summer Time */
248         {"magt", TZ, POS(44)},          /* Magadan Time */
249         {"mar", MONTH, 3},
250         {"march", MONTH, 3},
251         {"mart", TZ, NEG(38)},          /* Marquesas Time */
252         {"mawt", TZ, POS(24)},          /* Mawson, Antarctica */
253         {"may", MONTH, 5},
254         {"mdt", DTZ, NEG(24)},          /* Mountain Daylight Time */
255         {"mest", DTZ, POS(8)},          /* Middle Europe Summer Time */
256         {"met", TZ, POS(4)},            /* Middle Europe Time */
257         {"metdst", DTZ, POS(8)},        /* Middle Europe Daylight Time */
258         {"mewt", TZ, POS(4)},           /* Middle Europe Winter Time */
259         {"mez", TZ, POS(4)},            /* Middle Europe Zone */
260         {"mht", TZ, POS(48)},           /* Kwajalein */
261         {"mm", UNITS, DTK_MINUTE},      /* "minute" for ISO input */
262         {"mmt", TZ, POS(26)},           /* Myannar Time */
263         {"mon", DOW, 1},
264         {"monday", DOW, 1},
265 #if 0
266         most
267 #endif
268         {"mpt", TZ, POS(40)},           /* North Mariana Islands Time */
269         {"msd", DTZ, POS(16)},          /* Moscow Summer Time */
270         {"msk", TZ, POS(12)},           /* Moscow Time */
271         {"mst", TZ, NEG(28)},           /* Mountain Standard Time */
272         {"mt", TZ, POS(34)},            /* Moluccas Time */
273         {"mut", TZ, POS(16)},           /* Mauritius Island Time */
274         {"mvt", TZ, POS(20)},           /* Maldives Island Time */
275         {"myt", TZ, POS(32)},           /* Malaysia Time */
276 #if 0
277         ncst
278 #endif
279         {"nct", TZ, POS(44)},           /* New Caledonia Time */
280         {"ndt", DTZ, NEG(10)},          /* Nfld. Daylight Time */
281         {"nft", TZ, NEG(14)},           /* Newfoundland Standard Time */
282         {"nor", TZ, POS(4)},            /* Norway Standard Time */
283         {"nov", MONTH, 11},
284         {"november", MONTH, 11},
285         {"novst", DTZ, POS(28)},        /* Novosibirsk Summer Time */
286         {"novt", TZ, POS(24)},          /* Novosibirsk Standard Time */
287         {NOW, RESERV, DTK_NOW},         /* current transaction time */
288         {"npt", TZ, POS(23)},           /* Nepal Standard Time (GMT-5:45) */
289         {"nst", TZ, NEG(14)},           /* Nfld. Standard Time */
290         {"nt", TZ, NEG(44)},            /* Nome Time */
291         {"nut", TZ, NEG(44)},           /* Niue Time */
292         {"nzdt", DTZ, POS(52)},         /* New Zealand Daylight Time */
293         {"nzst", TZ, POS(48)},          /* New Zealand Standard Time */
294         {"nzt", TZ, POS(48)},           /* New Zealand Time */
295         {"oct", MONTH, 10},
296         {"october", MONTH, 10},
297         {"omsst", DTZ, POS(28)},        /* Omsk Summer Time */
298         {"omst", TZ, POS(24)},          /* Omsk Time */
299         {"on", IGNORE_DTF, 0},          /* "on" (throwaway) */
300         {"pdt", DTZ, NEG(28)},          /* Pacific Daylight Time */
301 #if 0
302         pest
303 #endif
304         {"pet", TZ, NEG(20)},           /* Peru Time */
305         {"petst", DTZ, POS(52)},        /* Petropavlovsk-Kamchatski Summer Time */
306         {"pett", TZ, POS(48)},          /* Petropavlovsk-Kamchatski Time */
307         {"pgt", TZ, POS(40)},           /* Papua New Guinea Time */
308         {"phot", TZ, POS(52)},          /* Phoenix Islands (Kiribati) Time */
309 #if 0
310         phst
311 #endif
312         {"pht", TZ, POS(32)},           /* Phillipine Time */
313         {"pkt", TZ, POS(20)},           /* Pakistan Time */
314         {"pm", AMPM, PM},
315         {"pmdt", DTZ, NEG(8)},          /* Pierre & Miquelon Daylight Time */
316 #if 0
317         pmst
318 #endif
319         {"pont", TZ, POS(44)},          /* Ponape Time (Micronesia) */
320         {"pst", TZ, NEG(32)},           /* Pacific Standard Time */
321         {"pwt", TZ, POS(36)},           /* Palau Time */
322         {"pyst", DTZ, NEG(12)},         /* Paraguay Summer Time */
323         {"pyt", TZ, NEG(16)},           /* Paraguay Time */
324         {"ret", DTZ, POS(16)},          /* Reunion Island Time */
325         {"s", UNITS, DTK_SECOND},       /* "seconds" for ISO input */
326         {"sadt", DTZ, POS(42)},         /* S. Australian Dayl. Time */
327 #if 0
328         samst
329         samt
330 #endif
331         {"sast", TZ, POS(38)},          /* South Australian Std Time */
332         {"sat", DOW, 6},
333         {"saturday", DOW, 6},
334 #if 0
335         sbt
336 #endif
337         {"sct", DTZ, POS(16)},          /* Mahe Island Time */
338         {"sep", MONTH, 9},
339         {"sept", MONTH, 9},
340         {"september", MONTH, 9},
341         {"set", TZ, NEG(4)},            /* Seychelles Time ?? */
342 #if 0
343         sgt
344 #endif
345         {"sst", DTZ, POS(8)},           /* Swedish Summer Time */
346         {"sun", DOW, 0},
347         {"sunday", DOW, 0},
348         {"swt", TZ, POS(4)},            /* Swedish Winter Time */
349 #if 0
350         syot
351 #endif
352         {"t", ISOTIME, DTK_TIME},       /* Filler for ISO time fields */
353         {"tft", TZ, POS(20)},           /* Kerguelen Time */
354         {"that", TZ, NEG(40)},          /* Tahiti Time */
355         {"thu", DOW, 4},
356         {"thur", DOW, 4},
357         {"thurs", DOW, 4},
358         {"thursday", DOW, 4},
359         {"tjt", TZ, POS(20)},           /* Tajikistan Time */
360         {"tkt", TZ, NEG(40)},           /* Tokelau Time */
361         {"tmt", TZ, POS(20)},           /* Turkmenistan Time */
362         {TODAY, RESERV, DTK_TODAY}, /* midnight */
363         {TOMORROW, RESERV, DTK_TOMORROW},       /* tomorrow midnight */
364 #if 0
365         tost
366 #endif
367         {"tot", TZ, POS(52)},           /* Tonga Time */
368 #if 0
369         tpt
370 #endif
371         {"truk", TZ, POS(40)},          /* Truk Time */
372         {"tue", DOW, 2},
373         {"tues", DOW, 2},
374         {"tuesday", DOW, 2},
375         {"tvt", TZ, POS(48)},           /* Tuvalu Time */
376 #if 0
377         uct
378 #endif
379         {"ulast", DTZ, POS(36)},        /* Ulan Bator Summer Time */
380         {"ulat", TZ, POS(32)},          /* Ulan Bator Time */
381         {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
382         {"ut", TZ, POS(0)},
383         {"utc", TZ, POS(0)},
384         {"uyst", DTZ, NEG(8)},          /* Uruguay Summer Time */
385         {"uyt", TZ, NEG(12)},           /* Uruguay Time */
386         {"uzst", DTZ, POS(24)},         /* Uzbekistan Summer Time */
387         {"uzt", TZ, POS(20)},           /* Uzbekistan Time */
388         {"vet", TZ, NEG(16)},           /* Venezuela Time */
389         {"vlast", DTZ, POS(44)},        /* Vladivostok Summer Time */
390         {"vlat", TZ, POS(40)},          /* Vladivostok Time */
391 #if 0
392         vust
393 #endif
394         {"vut", TZ, POS(44)},           /* Vanuata Time */
395         {"wadt", DTZ, POS(32)},         /* West Australian DST */
396         {"wakt", TZ, POS(48)},          /* Wake Time */
397 #if 0
398         warst
399 #endif
400         {"wast", TZ, POS(28)},          /* West Australian Std Time */
401         {"wat", TZ, NEG(4)},            /* West Africa Time */
402         {"wdt", DTZ, POS(36)},          /* West Australian DST */
403         {"wed", DOW, 3},
404         {"wednesday", DOW, 3},
405         {"weds", DOW, 3},
406         {"west", DTZ, POS(4)},          /* Western Europe Summer Time */
407         {"wet", TZ, POS(0)},            /* Western Europe */
408         {"wetdst", DTZ, POS(4)},        /* Western Europe Daylight Savings Time */
409         {"wft", TZ, POS(48)},           /* Wallis and Futuna Time */
410         {"wgst", DTZ, NEG(8)},          /* West Greenland Summer Time */
411         {"wgt", TZ, NEG(12)},           /* West Greenland Time */
412         {"wst", TZ, POS(32)},           /* West Australian Standard Time */
413         {"y", UNITS, DTK_YEAR},         /* "year" for ISO input */
414         {"yakst", DTZ, POS(40)},        /* Yakutsk Summer Time */
415         {"yakt", TZ, POS(36)},          /* Yakutsk Time */
416         {"yapt", TZ, POS(40)},          /* Yap Time (Micronesia) */
417         {"ydt", DTZ, NEG(32)},          /* Yukon Daylight Time */
418         {"yekst", DTZ, POS(24)},        /* Yekaterinburg Summer Time */
419         {"yekt", TZ, POS(20)},          /* Yekaterinburg Time */
420         {YESTERDAY, RESERV, DTK_YESTERDAY}, /* yesterday midnight */
421         {"yst", TZ, NEG(36)},           /* Yukon Standard Time */
422         {"z", TZ, POS(0)},                      /* time zone tag per ISO-8601 */
423         {"zp4", TZ, NEG(16)},           /* UTC +4  hours. */
424         {"zp5", TZ, NEG(20)},           /* UTC +5  hours. */
425         {"zp6", TZ, NEG(24)},           /* UTC +6  hours. */
426         {ZULU, TZ, POS(0)},                     /* UTC */
427 };
428
429 static datetkn deltatktbl[] = {
430         /* text, token, lexval */
431         {"@", IGNORE_DTF, 0},           /* postgres relative prefix */
432         {DAGO, AGO, 0},                         /* "ago" indicates negative time offset */
433         {"c", UNITS, DTK_CENTURY},      /* "century" relative */
434         {"cent", UNITS, DTK_CENTURY},           /* "century" relative */
435         {"centuries", UNITS, DTK_CENTURY},      /* "centuries" relative */
436         {DCENTURY, UNITS, DTK_CENTURY},         /* "century" relative */
437         {"d", UNITS, DTK_DAY},          /* "day" relative */
438         {DDAY, UNITS, DTK_DAY},         /* "day" relative */
439         {"days", UNITS, DTK_DAY},       /* "days" relative */
440         {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
441         {DDECADE, UNITS, DTK_DECADE},           /* "decade" relative */
442         {"decades", UNITS, DTK_DECADE},         /* "decades" relative */
443         {"decs", UNITS, DTK_DECADE},    /* "decades" relative */
444         {"h", UNITS, DTK_HOUR},         /* "hour" relative */
445         {DHOUR, UNITS, DTK_HOUR},       /* "hour" relative */
446         {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
447         {"hr", UNITS, DTK_HOUR},        /* "hour" relative */
448         {"hrs", UNITS, DTK_HOUR},       /* "hours" relative */
449         {INVALID, RESERV, DTK_INVALID},         /* reserved for invalid time */
450         {"m", UNITS, DTK_MINUTE},       /* "minute" relative */
451         {"microsecon", UNITS, DTK_MICROSEC},            /* "microsecond" relative */
452         {"mil", UNITS, DTK_MILLENNIUM},         /* "millennium" relative */
453         {"millennia", UNITS, DTK_MILLENNIUM},           /* "millennia" relative */
454         {DMILLENNIUM, UNITS, DTK_MILLENNIUM},           /* "millennium" relative */
455         {"millisecon", UNITS, DTK_MILLISEC},            /* relative */
456         {"mils", UNITS, DTK_MILLENNIUM},        /* "millennia" relative */
457         {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
458         {"mins", UNITS, DTK_MINUTE},    /* "minutes" relative */
459         {DMINUTE, UNITS, DTK_MINUTE},           /* "minute" relative */
460         {"minutes", UNITS, DTK_MINUTE},         /* "minutes" relative */
461         {"mon", UNITS, DTK_MONTH},      /* "months" relative */
462         {"mons", UNITS, DTK_MONTH}, /* "months" relative */
463         {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
464         {"months", UNITS, DTK_MONTH},
465         {"ms", UNITS, DTK_MILLISEC},
466         {"msec", UNITS, DTK_MILLISEC},
467         {DMILLISEC, UNITS, DTK_MILLISEC},
468         {"mseconds", UNITS, DTK_MILLISEC},
469         {"msecs", UNITS, DTK_MILLISEC},
470         {"qtr", UNITS, DTK_QUARTER},    /* "quarter" relative */
471         {DQUARTER, UNITS, DTK_QUARTER},         /* "quarter" relative */
472         {"reltime", IGNORE_DTF, 0}, /* pre-v6.1 "Undefined Reltime" */
473         {"s", UNITS, DTK_SECOND},
474         {"sec", UNITS, DTK_SECOND},
475         {DSECOND, UNITS, DTK_SECOND},
476         {"seconds", UNITS, DTK_SECOND},
477         {"secs", UNITS, DTK_SECOND},
478         {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
479         {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
480         {"timezone_m", UNITS, DTK_TZ_MINUTE},           /* timezone minutes units */
481         {"undefined", RESERV, DTK_INVALID}, /* pre-v6.1 invalid time */
482         {"us", UNITS, DTK_MICROSEC},    /* "microsecond" relative */
483         {"usec", UNITS, DTK_MICROSEC},          /* "microsecond" relative */
484         {DMICROSEC, UNITS, DTK_MICROSEC},       /* "microsecond" relative */
485         {"useconds", UNITS, DTK_MICROSEC},      /* "microseconds" relative */
486         {"usecs", UNITS, DTK_MICROSEC},         /* "microseconds" relative */
487         {"w", UNITS, DTK_WEEK},         /* "week" relative */
488         {DWEEK, UNITS, DTK_WEEK},       /* "week" relative */
489         {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
490         {"y", UNITS, DTK_YEAR},         /* "year" relative */
491         {DYEAR, UNITS, DTK_YEAR},       /* "year" relative */
492         {"years", UNITS, DTK_YEAR}, /* "years" relative */
493         {"yr", UNITS, DTK_YEAR},        /* "year" relative */
494         {"yrs", UNITS, DTK_YEAR},       /* "years" relative */
495 };
496
497 static unsigned int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0];
498 static unsigned int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0];
499
500 static datetkn *datecache[MAXDATEFIELDS] = {NULL};
501
502 static datetkn *deltacache[MAXDATEFIELDS] = {NULL};
503
504 char       *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};
505
506 char       *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", NULL};
507
508 char       *pgtypes_date_weekdays_short[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", NULL};
509
510 char       *pgtypes_date_months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", NULL};
511
512 static datetkn *
513 datebsearch(char *key, datetkn *base, unsigned int nel)
514 {
515         datetkn    *last = base + nel - 1,
516                            *position;
517         int                     result;
518
519         while (last >= base)
520         {
521                 position = base + ((last - base) >> 1);
522                 result = key[0] - position->token[0];
523                 if (result == 0)
524                 {
525                         result = strncmp(key, position->token, TOKMAXLEN);
526                         if (result == 0)
527                                 return position;
528                 }
529                 if (result < 0)
530                         last = position - 1;
531                 else
532                         base = position + 1;
533         }
534         return NULL;
535 }
536
537 /* DecodeUnits()
538  * Decode text string using lookup table.
539  * This routine supports time interval decoding.
540  */
541 int
542 DecodeUnits(int field, char *lowtoken, int *val)
543 {
544         int                     type;
545         datetkn    *tp;
546
547         if ((deltacache[field] != NULL)
548                 && (strncmp(lowtoken, deltacache[field]->token, TOKMAXLEN) == 0))
549                 tp = deltacache[field];
550         else
551                 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
552         deltacache[field] = tp;
553         if (tp == NULL)
554         {
555                 type = UNKNOWN_FIELD;
556                 *val = 0;
557         }
558         else
559         {
560                 type = tp->type;
561                 if ((type == TZ) || (type == DTZ))
562                         *val = FROMVAL(tp);
563                 else
564                         *val = tp->value;
565         }
566
567         return type;
568 }       /* DecodeUnits() */
569
570 /*
571  * Calendar time to Julian date conversions.
572  * Julian date is commonly used in astronomical applications,
573  *      since it is numerically accurate and computationally simple.
574  * The algorithms here will accurately convert between Julian day
575  *      and calendar date for all non-negative Julian days
576  *      (i.e. from Nov 24, -4713 on).
577  *
578  * These routines will be used by other date/time packages
579  * - thomas 97/02/25
580  *
581  * Rewritten to eliminate overflow problems. This now allows the
582  * routines to work correctly for all Julian day counts from
583  * 0 to 2147483647      (Nov 24, -4713 to Jun 3, 5874898) assuming
584  * a 32-bit integer. Longer types should also work to the limits
585  * of their precision.
586  */
587
588 int
589 date2j(int y, int m, int d)
590 {
591         int                     julian;
592         int                     century;
593
594         if (m > 2)
595         {
596                 m += 1;
597                 y += 4800;
598         }
599         else
600         {
601                 m += 13;
602                 y += 4799;
603         }
604
605         century = y / 100;
606         julian = y * 365 - 32167;
607         julian += y / 4 - century + century / 4;
608         julian += 7834 * m / 256 + d;
609
610         return julian;
611 }       /* date2j() */
612
613 void
614 j2date(int jd, int *year, int *month, int *day)
615 {
616         unsigned int julian;
617         unsigned int quad;
618         unsigned int extra;
619         int                     y;
620
621         julian = jd;
622         julian += 32044;
623         quad = julian / 146097;
624         extra = (julian - quad * 146097) * 4 + 3;
625         julian += 60 + quad * 3 + extra / 146097;
626         quad = julian / 1461;
627         julian -= quad * 1461;
628         y = julian * 4 / 1461;
629         julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
630                 + 123;
631         y += quad * 4;
632         *year = y - 4800;
633         quad = julian * 2141 / 65536;
634         *day = julian - 7834 * quad / 256;
635         *month = (quad + 10) % 12 + 1;
636
637         return;
638 }       /* j2date() */
639
640 int
641 j2day(int date)
642 {
643         unsigned int day;
644
645         day = date;
646         day += 1;
647         day %= 7;
648         return (int) day;
649 }       /* j2day() */
650
651 /* DecodeSpecial()
652  * Decode text string using lookup table.
653  * Implement a cache lookup since it is likely that dates
654  *      will be related in format.
655  */
656 static int
657 DecodeSpecial(int field, char *lowtoken, int *val)
658 {
659         int                     type;
660         datetkn    *tp;
661
662         if ((datecache[field] != NULL)
663                 && (strncmp(lowtoken, datecache[field]->token, TOKMAXLEN) == 0))
664                 tp = datecache[field];
665         else
666         {
667                 tp = NULL;
668                 if (!tp)
669                         tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
670         }
671         datecache[field] = tp;
672         if (tp == NULL)
673         {
674                 type = UNKNOWN_FIELD;
675                 *val = 0;
676         }
677         else
678         {
679                 type = tp->type;
680                 switch (type)
681                 {
682                         case TZ:
683                         case DTZ:
684                         case DTZMOD:
685                                 *val = FROMVAL(tp);
686                                 break;
687
688                         default:
689                                 *val = tp->value;
690                                 break;
691                 }
692         }
693
694         return type;
695 }       /* DecodeSpecial() */
696
697 /* EncodeDateOnly()
698  * Encode date as local time.
699  */
700 int
701 EncodeDateOnly(struct tm * tm, int style, char *str, bool EuroDates)
702 {
703         if ((tm->tm_mon < 1) || (tm->tm_mon > 12))
704                 return -1;
705
706         switch (style)
707         {
708                 case USE_ISO_DATES:
709                         /* compatible with ISO date formats */
710                         if (tm->tm_year > 0)
711                                 sprintf(str, "%04d-%02d-%02d",
712                                                 tm->tm_year, tm->tm_mon, tm->tm_mday);
713                         else
714                                 sprintf(str, "%04d-%02d-%02d %s",
715                                           -(tm->tm_year - 1), tm->tm_mon, tm->tm_mday, "BC");
716                         break;
717
718                 case USE_SQL_DATES:
719                         /* compatible with Oracle/Ingres date formats */
720                         if (EuroDates)
721                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
722                         else
723                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
724                         if (tm->tm_year > 0)
725                                 sprintf((str + 5), "/%04d", tm->tm_year);
726                         else
727                                 sprintf((str + 5), "/%04d %s", -(tm->tm_year - 1), "BC");
728                         break;
729
730                 case USE_GERMAN_DATES:
731                         /* German-style date format */
732                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
733                         if (tm->tm_year > 0)
734                                 sprintf((str + 5), ".%04d", tm->tm_year);
735                         else
736                                 sprintf((str + 5), ".%04d %s", -(tm->tm_year - 1), "BC");
737                         break;
738
739                 case USE_POSTGRES_DATES:
740                 default:
741                         /* traditional date-only style for Postgres */
742                         if (EuroDates)
743                                 sprintf(str, "%02d-%02d", tm->tm_mday, tm->tm_mon);
744                         else
745                                 sprintf(str, "%02d-%02d", tm->tm_mon, tm->tm_mday);
746                         if (tm->tm_year > 0)
747                                 sprintf((str + 5), "-%04d", tm->tm_year);
748                         else
749                                 sprintf((str + 5), "-%04d %s", -(tm->tm_year - 1), "BC");
750                         break;
751         }
752
753         return TRUE;
754 }       /* EncodeDateOnly() */
755
756 static void
757 TrimTrailingZeros(char *str)
758 {
759         int                     len = strlen(str);
760
761         /* chop off trailing zeros... but leave at least 2 fractional digits */
762         while ((*(str + len - 1) == '0') && (*(str + len - 3) != '.'))
763         {
764                 len--;
765                 *(str + len) = '\0';
766         }
767 }
768
769 /* EncodeDateTime()
770  * Encode date and time interpreted as local time.
771  * Support several date styles:
772  *      Postgres - day mon hh:mm:ss yyyy tz
773  *      SQL - mm/dd/yyyy hh:mm:ss.ss tz
774  *      ISO - yyyy-mm-dd hh:mm:ss+/-tz
775  *      German - dd.mm.yyyy hh:mm:ss tz
776  * Variants (affects order of month and day for Postgres and SQL styles):
777  *      US - mm/dd/yyyy
778  *      European - dd/mm/yyyy
779  */
780 int
781 EncodeDateTime(struct tm * tm, fsec_t fsec, int *tzp, char **tzn, int style, char *str, bool EuroDates)
782 {
783         int                     day,
784                                 hour,
785                                 min;
786
787         switch (style)
788         {
789                 case USE_ISO_DATES:
790                         /* Compatible with ISO-8601 date formats */
791
792                         sprintf(str, "%04d-%02d-%02d %02d:%02d",
793                                   ((tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1)),
794                                         tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min);
795
796                         /*
797                          * Print fractional seconds if any.  The field widths here
798                          * should be at least equal to MAX_TIMESTAMP_PRECISION.
799                          *
800                          * In float mode, don't print fractional seconds before 1 AD,
801                          * since it's unlikely there's any precision left ...
802                          */
803 #ifdef HAVE_INT64_TIMESTAMP
804                         if (fsec != 0)
805                         {
806                                 sprintf((str + strlen(str)), ":%02d.%06d", tm->tm_sec, fsec);
807 #else
808                         if ((fsec != 0) && (tm->tm_year > 0))
809                         {
810                                 sprintf((str + strlen(str)), ":%09.6f", tm->tm_sec + fsec);
811 #endif
812                                 TrimTrailingZeros(str);
813                         }
814                         else
815                                 sprintf((str + strlen(str)), ":%02d", tm->tm_sec);
816
817                         if (tm->tm_year <= 0)
818                                 sprintf((str + strlen(str)), " BC");
819
820                         /*
821                          * tzp == NULL indicates that we don't want *any* time zone
822                          * info in the output string. *tzn != NULL indicates that we
823                          * have alpha time zone info available. tm_isdst != -1
824                          * indicates that we have a valid time zone translation.
825                          */
826                         if ((tzp != NULL) && (tm->tm_isdst >= 0))
827                         {
828                                 hour = -(*tzp / 3600);
829                                 min = ((abs(*tzp) / 60) % 60);
830                                 sprintf((str + strlen(str)), ((min != 0) ? "%+03d:%02d" : "%+03d"), hour, min);
831                         }
832                         break;
833
834                 case USE_SQL_DATES:
835                         /* Compatible with Oracle/Ingres date formats */
836
837                         if (EuroDates)
838                                 sprintf(str, "%02d/%02d", tm->tm_mday, tm->tm_mon);
839                         else
840                                 sprintf(str, "%02d/%02d", tm->tm_mon, tm->tm_mday);
841
842                         sprintf((str + 5), "/%04d %02d:%02d",
843                                   ((tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1)),
844                                         tm->tm_hour, tm->tm_min);
845
846                         /*
847                          * Print fractional seconds if any.  The field widths here
848                          * should be at least equal to MAX_TIMESTAMP_PRECISION.
849                          *
850                          * In float mode, don't print fractional seconds before 1 AD,
851                          * since it's unlikely there's any precision left ...
852                          */
853 #ifdef HAVE_INT64_TIMESTAMP
854                         if (fsec != 0)
855                         {
856                                 sprintf((str + strlen(str)), ":%02d.%06d", tm->tm_sec, fsec);
857 #else
858                         if ((fsec != 0) && (tm->tm_year > 0))
859                         {
860                                 sprintf((str + strlen(str)), ":%09.6f", tm->tm_sec + fsec);
861 #endif
862                                 TrimTrailingZeros(str);
863                         }
864                         else
865                                 sprintf((str + strlen(str)), ":%02d", tm->tm_sec);
866
867                         if (tm->tm_year <= 0)
868                                 sprintf((str + strlen(str)), " BC");
869
870                         if ((tzp != NULL) && (tm->tm_isdst >= 0))
871                         {
872                                 if (*tzn != NULL)
873                                         sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn);
874                                 else
875                                 {
876                                         hour = -(*tzp / 3600);
877                                         min = ((abs(*tzp) / 60) % 60);
878                                         sprintf((str + strlen(str)), ((min != 0) ? "%+03d:%02d" : "%+03d"), hour, min);
879                                 }
880                         }
881                         break;
882
883                 case USE_GERMAN_DATES:
884                         /* German variant on European style */
885
886                         sprintf(str, "%02d.%02d", tm->tm_mday, tm->tm_mon);
887
888                         sprintf((str + 5), ".%04d %02d:%02d",
889                                   ((tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1)),
890                                         tm->tm_hour, tm->tm_min);
891
892                         /*
893                          * Print fractional seconds if any.  The field widths here
894                          * should be at least equal to MAX_TIMESTAMP_PRECISION.
895                          *
896                          * In float mode, don't print fractional seconds before 1 AD,
897                          * since it's unlikely there's any precision left ...
898                          */
899 #ifdef HAVE_INT64_TIMESTAMP
900                         if (fsec != 0)
901                         {
902                                 sprintf((str + strlen(str)), ":%02d.%06d", tm->tm_sec, fsec);
903 #else
904                         if ((fsec != 0) && (tm->tm_year > 0))
905                         {
906                                 sprintf((str + strlen(str)), ":%09.6f", tm->tm_sec + fsec);
907 #endif
908                                 TrimTrailingZeros(str);
909                         }
910                         else
911                                 sprintf((str + strlen(str)), ":%02d", tm->tm_sec);
912
913                         if (tm->tm_year <= 0)
914                                 sprintf((str + strlen(str)), " BC");
915
916                         if ((tzp != NULL) && (tm->tm_isdst >= 0))
917                         {
918                                 if (*tzn != NULL)
919                                         sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn);
920                                 else
921                                 {
922                                         hour = -(*tzp / 3600);
923                                         min = ((abs(*tzp) / 60) % 60);
924                                         sprintf((str + strlen(str)), ((min != 0) ? "%+03d:%02d" : "%+03d"), hour, min);
925                                 }
926                         }
927                         break;
928
929                 case USE_POSTGRES_DATES:
930                 default:
931                         /* Backward-compatible with traditional Postgres abstime dates */
932
933                         day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
934                         tm->tm_wday = j2day(day);
935
936                         strncpy(str, days[tm->tm_wday], 3);
937                         strcpy((str + 3), " ");
938
939                         if (EuroDates)
940                                 sprintf((str + 4), "%02d %3s", tm->tm_mday, months[tm->tm_mon - 1]);
941                         else
942                                 sprintf((str + 4), "%3s %02d", months[tm->tm_mon - 1], tm->tm_mday);
943
944                         sprintf((str + 10), " %02d:%02d", tm->tm_hour, tm->tm_min);
945
946                         /*
947                          * Print fractional seconds if any.  The field widths here
948                          * should be at least equal to MAX_TIMESTAMP_PRECISION.
949                          *
950                          * In float mode, don't print fractional seconds before 1 AD,
951                          * since it's unlikely there's any precision left ...
952                          */
953 #ifdef HAVE_INT64_TIMESTAMP
954                         if (fsec != 0)
955                         {
956                                 sprintf((str + strlen(str)), ":%02d.%06d", tm->tm_sec, fsec);
957 #else
958                         if ((fsec != 0) && (tm->tm_year > 0))
959                         {
960                                 sprintf((str + strlen(str)), ":%09.6f", tm->tm_sec + fsec);
961 #endif
962                                 TrimTrailingZeros(str);
963                         }
964                         else
965                                 sprintf((str + strlen(str)), ":%02d", tm->tm_sec);
966
967                         sprintf((str + strlen(str)), " %04d",
968                                  ((tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1)));
969                         if (tm->tm_year <= 0)
970                                 sprintf((str + strlen(str)), " BC");
971
972                         if ((tzp != NULL) && (tm->tm_isdst >= 0))
973                         {
974                                 if (*tzn != NULL)
975                                         sprintf((str + strlen(str)), " %.*s", MAXTZLEN, *tzn);
976                                 else
977                                 {
978                                         /*
979                                          * We have a time zone, but no string version. Use the
980                                          * numeric form, but be sure to include a leading
981                                          * space to avoid formatting something which would be
982                                          * rejected by the date/time parser later. - thomas
983                                          * 2001-10-19
984                                          */
985                                         hour = -(*tzp / 3600);
986                                         min = ((abs(*tzp) / 60) % 60);
987                                         sprintf((str + strlen(str)), ((min != 0) ? " %+03d:%02d" : " %+03d"), hour, min);
988                                 }
989                         }
990                         break;
991         }
992
993         return TRUE;
994 }       /* EncodeDateTime() */
995
996 void
997 GetEpochTime(struct tm * tm)
998 {
999         struct tm  *t0;
1000         time_t          epoch = 0;
1001
1002         t0 = gmtime(&epoch);
1003
1004         tm->tm_year = t0->tm_year;
1005         tm->tm_mon = t0->tm_mon;
1006         tm->tm_mday = t0->tm_mday;
1007         tm->tm_hour = t0->tm_hour;
1008         tm->tm_min = t0->tm_min;
1009         tm->tm_sec = t0->tm_sec;
1010
1011         if (tm->tm_year < 1900)
1012                 tm->tm_year += 1900;
1013         tm->tm_mon++;
1014
1015         return;
1016 }       /* GetEpochTime() */
1017
1018 static void
1019 abstime2tm(AbsoluteTime _time, int *tzp, struct tm * tm, char **tzn)
1020 {
1021         time_t          time = (time_t) _time;
1022         struct tm  *tx;
1023
1024         if (tzp != NULL)
1025                 tx = localtime((time_t *) &time);
1026         else
1027                 tx = gmtime((time_t *) &time);
1028
1029         tm->tm_year = tx->tm_year + 1900;
1030         tm->tm_mon = tx->tm_mon + 1;
1031         tm->tm_mday = tx->tm_mday;
1032         tm->tm_hour = tx->tm_hour;
1033         tm->tm_min = tx->tm_min;
1034         tm->tm_sec = tx->tm_sec;
1035         tm->tm_isdst = tx->tm_isdst;
1036
1037 #if defined(HAVE_TM_ZONE)
1038         tm->tm_gmtoff = tx->tm_gmtoff;
1039         tm->tm_zone = tx->tm_zone;
1040
1041         if (tzp != NULL)
1042         {
1043                 /*
1044                  * We have a brute force time zone per SQL99? Then use it without
1045                  * change since we have already rotated to the time zone.
1046                  */
1047                 *tzp = -tm->tm_gmtoff;  /* tm_gmtoff is Sun/DEC-ism */
1048
1049                 /*
1050                  * XXX FreeBSD man pages indicate that this should work - tgl
1051                  * 97/04/23
1052                  */
1053                 if (tzn != NULL)
1054                 {
1055                         /*
1056                          * Copy no more than MAXTZLEN bytes of timezone to tzn, in
1057                          * case it contains an error message, which doesn't fit in the
1058                          * buffer
1059                          */
1060                         StrNCpy(*tzn, tm->tm_zone, MAXTZLEN + 1);
1061                         if (strlen(tm->tm_zone) > MAXTZLEN)
1062                                 tm->tm_isdst = -1;
1063                 }
1064         }
1065         else
1066                 tm->tm_isdst = -1;
1067 #elif defined(HAVE_INT_TIMEZONE)
1068         if (tzp != NULL)
1069         {
1070                 *tzp = ((tm->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
1071
1072                 if (tzn != NULL)
1073                 {
1074                         /*
1075                          * Copy no more than MAXTZLEN bytes of timezone to tzn, in
1076                          * case it contains an error message, which doesn't fit in the
1077                          * buffer
1078                          */
1079                         StrNCpy(*tzn, tzname[tm->tm_isdst], MAXTZLEN + 1);
1080                         if (strlen(tzname[tm->tm_isdst]) > MAXTZLEN)
1081                                 tm->tm_isdst = -1;
1082                 }
1083         }
1084         else
1085                 tm->tm_isdst = -1;
1086 #else                                                   /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
1087         if (tzp != NULL)
1088         {
1089                 /* default to UTC */
1090                 *tzp = 0;
1091                 if (tzn != NULL)
1092                         *tzn = NULL;
1093         }
1094         else
1095                 tm->tm_isdst = -1;
1096 #endif
1097 }
1098
1099 void
1100 GetCurrentDateTime(struct tm * tm)
1101 {
1102         int                     tz;
1103
1104         abstime2tm(time(NULL), &tz, tm, NULL);
1105 }
1106
1107 /* DetermineLocalTimeZone()
1108  *
1109  * Given a struct tm in which tm_year, tm_mon, tm_mday, tm_hour, tm_min, and
1110  * tm_sec fields are set, attempt to determine the applicable local zone
1111  * (ie, regular or daylight-savings time) at that time.  Set the struct tm's
1112  * tm_isdst field accordingly, and return the actual timezone offset.
1113  *
1114  * This subroutine exists to centralize uses of mktime() and defend against
1115  * mktime() bugs/restrictions on various platforms.  This should be
1116  * the *only* call of mktime() in the backend.
1117  */
1118 static int
1119 DetermineLocalTimeZone(struct tm * tm)
1120 {
1121         int                     tz;
1122
1123         if (IS_VALID_UTIME(tm->tm_year, tm->tm_mon, tm->tm_mday))
1124         {
1125 #if defined(HAVE_TM_ZONE) || defined(HAVE_INT_TIMEZONE)
1126
1127                 /*
1128                  * Some buggy mktime() implementations may change the
1129                  * year/month/day when given a time right at a DST boundary.  To
1130                  * prevent corruption of the caller's data, give mktime() a
1131                  * copy...
1132                  */
1133                 struct tm       tt,
1134                                    *tmp = &tt;
1135
1136                 *tmp = *tm;
1137                 /* change to Unix conventions for year/month */
1138                 tmp->tm_year -= 1900;
1139                 tmp->tm_mon -= 1;
1140
1141                 /* indicate timezone unknown */
1142                 tmp->tm_isdst = -1;
1143
1144                 if (mktime(tmp) != ((time_t) -1) &&
1145                         tmp->tm_isdst >= 0)
1146                 {
1147                         /* mktime() succeeded, trust its result */
1148                         tm->tm_isdst = tmp->tm_isdst;
1149
1150 #if defined(HAVE_TM_ZONE)
1151                         /* tm_gmtoff is Sun/DEC-ism */
1152                         tz = -(tmp->tm_gmtoff);
1153 #elif defined(HAVE_INT_TIMEZONE)
1154                         tz = ((tmp->tm_isdst > 0) ? (TIMEZONE_GLOBAL - 3600) : TIMEZONE_GLOBAL);
1155 #endif   /* HAVE_INT_TIMEZONE */
1156                 }
1157                 else
1158                 {
1159                         /*
1160                          * We have a buggy (not to say deliberately brain damaged)
1161                          * mktime().  Work around it by using localtime() instead.
1162                          *
1163                          * First, generate the time_t value corresponding to the given
1164                          * y/m/d/h/m/s taken as GMT time.  This will not overflow (at
1165                          * least not for time_t taken as signed) because of the range
1166                          * check we did above.
1167                          */
1168                         long            day,
1169                                                 mysec,
1170                                                 locsec,
1171                                                 delta1,
1172                                                 delta2;
1173                         time_t          mytime;
1174
1175                         day = (date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) -
1176                                    date2j(1970, 1, 1));
1177                         mysec = tm->tm_sec + (tm->tm_min + (day * 24 + tm->tm_hour) * 60) * 60;
1178                         mytime = (time_t) mysec;
1179
1180                         /*
1181                          * Use localtime to convert that time_t to broken-down time,
1182                          * and reassemble to get a representation of local time.
1183                          */
1184                         tmp = localtime(&mytime);
1185                         day = (date2j(tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday) -
1186                                    date2j(1970, 1, 1));
1187                         locsec = tmp->tm_sec + (tmp->tm_min + (day * 24 + tmp->tm_hour) * 60) * 60;
1188
1189                         /*
1190                          * The local time offset corresponding to that GMT time is now
1191                          * computable as mysec - locsec.
1192                          */
1193                         delta1 = mysec - locsec;
1194
1195                         /*
1196                          * However, if that GMT time and the local time we are
1197                          * actually interested in are on opposite sides of a
1198                          * daylight-savings-time transition, then this is not the time
1199                          * offset we want.      So, adjust the time_t to be what we think
1200                          * the GMT time corresponding to our target local time is, and
1201                          * repeat the localtime() call and delta calculation.  We may
1202                          * have to do it twice before we have a trustworthy delta.
1203                          *
1204                          * Note: think not to put a loop here, since if we've been given
1205                          * an "impossible" local time (in the gap during a
1206                          * spring-forward transition) we'd never get out of the loop.
1207                          * Twice is enough to give the behavior we want, which is that
1208                          * "impossible" times are taken as standard time, while at a
1209                          * fall-back boundary ambiguous times are also taken as
1210                          * standard.
1211                          */
1212                         mysec += delta1;
1213                         mytime = (time_t) mysec;
1214                         tmp = localtime(&mytime);
1215                         day = (date2j(tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday) -
1216                                    date2j(1970, 1, 1));
1217                         locsec = tmp->tm_sec + (tmp->tm_min + (day * 24 + tmp->tm_hour) * 60) * 60;
1218                         delta2 = mysec - locsec;
1219                         if (delta2 != delta1)
1220                         {
1221                                 mysec += (delta2 - delta1);
1222                                 mytime = (time_t) mysec;
1223                                 tmp = localtime(&mytime);
1224                                 day = (date2j(tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday) -
1225                                            date2j(1970, 1, 1));
1226                                 locsec = tmp->tm_sec + (tmp->tm_min + (day * 24 + tmp->tm_hour) * 60) * 60;
1227                                 delta2 = mysec - locsec;
1228                         }
1229                         tm->tm_isdst = tmp->tm_isdst;
1230                         tz = (int) delta2;
1231                 }
1232 #else                                                   /* not (HAVE_TM_ZONE || HAVE_INT_TIMEZONE) */
1233                 /* Assume UTC if no system timezone info available */
1234                 tm->tm_isdst = 0;
1235                 tz = 0;
1236 #endif
1237         }
1238         else
1239         {
1240                 /* Given date is out of range, so assume UTC */
1241                 tm->tm_isdst = 0;
1242                 tz = 0;
1243         }
1244
1245         return tz;
1246 }
1247
1248 static void
1249 dt2time(double jd, int *hour, int *min, int *sec, fsec_t *fsec)
1250 {
1251 #ifdef HAVE_INT64_TIMESTAMP
1252         int64           time;
1253
1254 #else
1255         double          time;
1256 #endif
1257
1258         time = jd;
1259 #ifdef HAVE_INT64_TIMESTAMP
1260         *hour = (time / INT64CONST(3600000000));
1261         time -= ((*hour) * INT64CONST(3600000000));
1262         *min = (time / INT64CONST(60000000));
1263         time -= ((*min) * INT64CONST(60000000));
1264         *sec = (time / INT64CONST(1000000));
1265         *fsec = (time - (*sec * INT64CONST(1000000)));
1266 #else
1267         *hour = (time / 3600);
1268         time -= ((*hour) * 3600);
1269         *min = (time / 60);
1270         time -= ((*min) * 60);
1271         *sec = time;
1272         *fsec = JROUND(time - *sec);
1273 #endif
1274         return;
1275 }       /* dt2time() */
1276
1277
1278
1279 /* DecodeNumberField()
1280  * Interpret numeric string as a concatenated date or time field.
1281  * Use the context of previously decoded fields to help with
1282  * the interpretation.
1283  */
1284 static int
1285 DecodeNumberField(int len, char *str, int fmask,
1286 int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates)
1287 {
1288         char       *cp;
1289
1290         /*
1291          * Have a decimal point? Then this is a date or something with a
1292          * seconds field...
1293          */
1294         if ((cp = strchr(str, '.')) != NULL)
1295         {
1296 #ifdef HAVE_INT64_TIMESTAMP
1297                 char            fstr[MAXDATELEN + 1];
1298
1299                 /*
1300                  * OK, we have at most six digits to care about. Let's construct a
1301                  * string and then do the conversion to an integer.
1302                  */
1303                 strcpy(fstr, (cp + 1));
1304                 strcpy((fstr + strlen(fstr)), "000000");
1305                 *(fstr + 6) = '\0';
1306                 *fsec = strtol(fstr, NULL, 10);
1307 #else
1308                 *fsec = strtod(cp, NULL);
1309 #endif
1310                 *cp = '\0';
1311                 len = strlen(str);
1312         }
1313         /* No decimal point and no complete date yet? */
1314         else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1315         {
1316                 /* yyyymmdd? */
1317                 if (len == 8)
1318                 {
1319                         *tmask = DTK_DATE_M;
1320
1321                         tm->tm_mday = atoi(str + 6);
1322                         *(str + 6) = '\0';
1323                         tm->tm_mon = atoi(str + 4);
1324                         *(str + 4) = '\0';
1325                         tm->tm_year = atoi(str + 0);
1326
1327                         return DTK_DATE;
1328                 }
1329                 /* yymmdd? */
1330                 else if (len == 6)
1331                 {
1332                         *tmask = DTK_DATE_M;
1333                         tm->tm_mday = atoi(str + 4);
1334                         *(str + 4) = '\0';
1335                         tm->tm_mon = atoi(str + 2);
1336                         *(str + 2) = '\0';
1337                         tm->tm_year = atoi(str + 0);
1338                         *is2digits = TRUE;
1339
1340                         return DTK_DATE;
1341                 }
1342                 /* yyddd? */
1343                 else if (len == 5)
1344                 {
1345                         *tmask = DTK_DATE_M;
1346                         tm->tm_mday = atoi(str + 2);
1347                         *(str + 2) = '\0';
1348                         tm->tm_mon = 1;
1349                         tm->tm_year = atoi(str + 0);
1350                         *is2digits = TRUE;
1351
1352                         return DTK_DATE;
1353                 }
1354         }
1355
1356         /* not all time fields are specified? */
1357         if ((fmask & DTK_TIME_M) != DTK_TIME_M)
1358         {
1359                 /* hhmmss */
1360                 if (len == 6)
1361                 {
1362                         *tmask = DTK_TIME_M;
1363                         tm->tm_sec = atoi(str + 4);
1364                         *(str + 4) = '\0';
1365                         tm->tm_min = atoi(str + 2);
1366                         *(str + 2) = '\0';
1367                         tm->tm_hour = atoi(str + 0);
1368
1369                         return DTK_TIME;
1370                 }
1371                 /* hhmm? */
1372                 else if (len == 4)
1373                 {
1374                         *tmask = DTK_TIME_M;
1375                         tm->tm_sec = 0;
1376                         tm->tm_min = atoi(str + 2);
1377                         *(str + 2) = '\0';
1378                         tm->tm_hour = atoi(str + 0);
1379
1380                         return DTK_TIME;
1381                 }
1382         }
1383
1384         return -1;
1385 }       /* DecodeNumberField() */
1386
1387
1388 /* DecodeNumber()
1389  * Interpret plain numeric field as a date value in context.
1390  */
1391 static int
1392 DecodeNumber(int flen, char *str, int fmask,
1393 int *tmask, struct tm * tm, fsec_t *fsec, int *is2digits, bool EuroDates)
1394 {
1395         int                     val;
1396         char       *cp;
1397
1398         *tmask = 0;
1399
1400         val = strtol(str, &cp, 10);
1401         if (cp == str)
1402                 return -1;
1403
1404         if (*cp == '.')
1405         {
1406                 /*
1407                  * More than two digits? Then could be a date or a run-together
1408                  * time: 2001.360 20011225 040506.789
1409                  */
1410                 if ((cp - str) > 2)
1411                         return DecodeNumberField(flen, str, (fmask | DTK_DATE_M),
1412                                                                   tmask, tm, fsec, is2digits, EuroDates);
1413
1414                 *fsec = strtod(cp, &cp);
1415                 if (*cp != '\0')
1416                         return -1;
1417         }
1418         else if (*cp != '\0')
1419                 return -1;
1420
1421         /* Special case day of year? */
1422         if ((flen == 3) && (fmask & DTK_M(YEAR))
1423                 && ((val >= 1) && (val <= 366)))
1424         {
1425                 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
1426                 tm->tm_yday = val;
1427                 j2date((date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1),
1428                            &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1429         }
1430
1431         /***
1432          * Enough digits to be unequivocal year? Used to test for 4 digits or
1433          * more, but we now test first for a three-digit doy so anything
1434          * bigger than two digits had better be an explicit year.
1435          * - thomas 1999-01-09
1436          * Back to requiring a 4 digit year. We accept a two digit
1437          * year farther down. - thomas 2000-03-28
1438          ***/
1439         else if (flen >= 4)
1440         {
1441                 *tmask = DTK_M(YEAR);
1442
1443                 /* already have a year? then see if we can substitute... */
1444                 if ((fmask & DTK_M(YEAR)) && (!(fmask & DTK_M(DAY)))
1445                         && ((tm->tm_year >= 1) && (tm->tm_year <= 31)))
1446                 {
1447                         tm->tm_mday = tm->tm_year;
1448                         *tmask = DTK_M(DAY);
1449                 }
1450
1451                 tm->tm_year = val;
1452         }
1453
1454         /* already have year? then could be month */
1455         else if ((fmask & DTK_M(YEAR)) && (!(fmask & DTK_M(MONTH)))
1456                          && ((val >= 1) && (val <= 12)))
1457         {
1458                 *tmask = DTK_M(MONTH);
1459                 tm->tm_mon = val;
1460         }
1461         /* no year and EuroDates enabled? then could be day */
1462         else if ((EuroDates || (fmask & DTK_M(MONTH)))
1463                          && (!(fmask & DTK_M(YEAR)) && !(fmask & DTK_M(DAY)))
1464                          && ((val >= 1) && (val <= 31)))
1465         {
1466                 *tmask = DTK_M(DAY);
1467                 tm->tm_mday = val;
1468         }
1469         else if ((!(fmask & DTK_M(MONTH)))
1470                          && ((val >= 1) && (val <= 12)))
1471         {
1472                 *tmask = DTK_M(MONTH);
1473                 tm->tm_mon = val;
1474         }
1475         else if ((!(fmask & DTK_M(DAY)))
1476                          && ((val >= 1) && (val <= 31)))
1477         {
1478                 *tmask = DTK_M(DAY);
1479                 tm->tm_mday = val;
1480         }
1481
1482         /*
1483          * Check for 2 or 4 or more digits, but currently we reach here only
1484          * if two digits. - thomas 2000-03-28
1485          */
1486         else if (!(fmask & DTK_M(YEAR))
1487                          && ((flen >= 4) || (flen == 2)))
1488         {
1489                 *tmask = DTK_M(YEAR);
1490                 tm->tm_year = val;
1491
1492                 /* adjust ONLY if exactly two digits... */
1493                 *is2digits = (flen == 2);
1494         }
1495         else
1496                 return -1;
1497
1498         return 0;
1499 }       /* DecodeNumber() */
1500
1501 /* DecodeDate()
1502  * Decode date string which includes delimiters.
1503  * Insist on a complete set of fields.
1504  */
1505 static int
1506 DecodeDate(char *str, int fmask, int *tmask, struct tm * tm, bool EuroDates)
1507 {
1508         fsec_t          fsec;
1509
1510         int                     nf = 0;
1511         int                     i,
1512                                 len;
1513         int                     bc = FALSE;
1514         int                     is2digits = FALSE;
1515         int                     type,
1516                                 val,
1517                                 dmask = 0;
1518         char       *field[MAXDATEFIELDS];
1519
1520         /* parse this string... */
1521         while ((*str != '\0') && (nf < MAXDATEFIELDS))
1522         {
1523                 /* skip field separators */
1524                 while (!isalnum((unsigned char) *str))
1525                         str++;
1526
1527                 field[nf] = str;
1528                 if (isdigit((unsigned char) *str))
1529                 {
1530                         while (isdigit((unsigned char) *str))
1531                                 str++;
1532                 }
1533                 else if (isalpha((unsigned char) *str))
1534                 {
1535                         while (isalpha((unsigned char) *str))
1536                                 str++;
1537                 }
1538
1539                 /* Just get rid of any non-digit, non-alpha characters... */
1540                 if (*str != '\0')
1541                         *str++ = '\0';
1542                 nf++;
1543         }
1544
1545 #if 0
1546         /* don't allow too many fields */
1547         if (nf > 3)
1548                 return -1;
1549 #endif
1550
1551         *tmask = 0;
1552
1553         /* look first for text fields, since that will be unambiguous month */
1554         for (i = 0; i < nf; i++)
1555         {
1556                 if (isalpha((unsigned char) *field[i]))
1557                 {
1558                         type = DecodeSpecial(i, field[i], &val);
1559                         if (type == IGNORE_DTF)
1560                                 continue;
1561
1562                         dmask = DTK_M(type);
1563                         switch (type)
1564                         {
1565                                 case MONTH:
1566                                         tm->tm_mon = val;
1567                                         break;
1568
1569                                 case ADBC:
1570                                         bc = (val == BC);
1571                                         break;
1572
1573                                 default:
1574                                         return -1;
1575                         }
1576                         if (fmask & dmask)
1577                                 return -1;
1578
1579                         fmask |= dmask;
1580                         *tmask |= dmask;
1581
1582                         /* mark this field as being completed */
1583                         field[i] = NULL;
1584                 }
1585         }
1586
1587         /* now pick up remaining numeric fields */
1588         for (i = 0; i < nf; i++)
1589         {
1590                 if (field[i] == NULL)
1591                         continue;
1592
1593                 if ((len = strlen(field[i])) <= 0)
1594                         return -1;
1595
1596                 if (DecodeNumber(len, field[i], fmask, &dmask, tm, &fsec, &is2digits, EuroDates) != 0)
1597                         return -1;
1598
1599                 if (fmask & dmask)
1600                         return -1;
1601
1602                 fmask |= dmask;
1603                 *tmask |= dmask;
1604         }
1605
1606         if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
1607                 return -1;
1608
1609         /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
1610         if (bc)
1611         {
1612                 if (tm->tm_year > 0)
1613                         tm->tm_year = -(tm->tm_year - 1);
1614                 else
1615                         return -1;
1616         }
1617         else if (is2digits)
1618         {
1619                 if (tm->tm_year < 70)
1620                         tm->tm_year += 2000;
1621                 else if (tm->tm_year < 100)
1622                         tm->tm_year += 1900;
1623         }
1624
1625         return 0;
1626 }       /* DecodeDate() */
1627
1628
1629 /* DecodeTime()
1630  * Decode time string which includes delimiters.
1631  * Only check the lower limit on hours, since this same code
1632  *      can be used to represent time spans.
1633  */
1634 static int
1635 DecodeTime(char *str, int fmask, int *tmask, struct tm * tm, fsec_t *fsec)
1636 {
1637         char       *cp;
1638
1639         *tmask = DTK_TIME_M;
1640
1641         tm->tm_hour = strtol(str, &cp, 10);
1642         if (*cp != ':')
1643                 return -1;
1644         str = cp + 1;
1645         tm->tm_min = strtol(str, &cp, 10);
1646         if (*cp == '\0')
1647         {
1648                 tm->tm_sec = 0;
1649                 *fsec = 0;
1650         }
1651         else if (*cp != ':')
1652                 return -1;
1653         else
1654         {
1655                 str = cp + 1;
1656                 tm->tm_sec = strtol(str, &cp, 10);
1657                 if (*cp == '\0')
1658                         *fsec = 0;
1659                 else if (*cp == '.')
1660                 {
1661 #ifdef HAVE_INT64_TIMESTAMP
1662                         char            fstr[MAXDATELEN + 1];
1663
1664                         /*
1665                          * OK, we have at most six digits to work with. Let's
1666                          * construct a string and then do the conversion to an
1667                          * integer.
1668                          */
1669                         strncpy(fstr, (cp + 1), 7);
1670                         strcpy((fstr + strlen(fstr)), "000000");
1671                         *(fstr + 6) = '\0';
1672                         *fsec = strtol(fstr, &cp, 10);
1673 #else
1674                         str = cp;
1675                         *fsec = strtod(str, &cp);
1676 #endif
1677                         if (*cp != '\0')
1678                                 return -1;
1679                 }
1680                 else
1681                         return -1;
1682         }
1683
1684         /* do a sanity check */
1685 #ifdef HAVE_INT64_TIMESTAMP
1686         if ((tm->tm_hour < 0)
1687                 || (tm->tm_min < 0) || (tm->tm_min > 59)
1688                 || (tm->tm_sec < 0) || (tm->tm_sec > 59)
1689                 || (*fsec >= INT64CONST(1000000)))
1690                 return -1;
1691 #else
1692         if ((tm->tm_hour < 0)
1693                 || (tm->tm_min < 0) || (tm->tm_min > 59)
1694                 || (tm->tm_sec < 0) || (tm->tm_sec > 59)
1695                 || (*fsec >= 1))
1696                 return -1;
1697 #endif
1698
1699         return 0;
1700 }       /* DecodeTime() */
1701
1702 /* DecodeTimezone()
1703  * Interpret string as a numeric timezone.
1704  *
1705  * Note: we allow timezone offsets up to 13:59.  There are places that
1706  * use +1300 summer time.
1707  */
1708 static int
1709 DecodeTimezone(char *str, int *tzp)
1710 {
1711         int                     tz;
1712         int                     hr,
1713                                 min;
1714         char       *cp;
1715         int                     len;
1716
1717         /* assume leading character is "+" or "-" */
1718         hr = strtol((str + 1), &cp, 10);
1719
1720         /* explicit delimiter? */
1721         if (*cp == ':')
1722                 min = strtol((cp + 1), &cp, 10);
1723         /* otherwise, might have run things together... */
1724         else if ((*cp == '\0') && ((len = strlen(str)) > 3))
1725         {
1726                 min = strtol((str + len - 2), &cp, 10);
1727                 if ((min < 0) || (min >= 60))
1728                         return -1;
1729
1730                 *(str + len - 2) = '\0';
1731                 hr = strtol((str + 1), &cp, 10);
1732                 if ((hr < 0) || (hr > 13))
1733                         return -1;
1734         }
1735         else
1736                 min = 0;
1737
1738         tz = (hr * 60 + min) * 60;
1739         if (*str == '-')
1740                 tz = -tz;
1741
1742         *tzp = -tz;
1743         return *cp != '\0';
1744 }       /* DecodeTimezone() */
1745
1746
1747 /* DecodePosixTimezone()
1748  * Interpret string as a POSIX-compatible timezone:
1749  *      PST-hh:mm
1750  *      PST+h
1751  * - thomas 2000-03-15
1752  */
1753 static int
1754 DecodePosixTimezone(char *str, int *tzp)
1755 {
1756         int                     val,
1757                                 tz;
1758         int                     type;
1759         char       *cp;
1760         char            delim;
1761
1762         cp = str;
1763         while ((*cp != '\0') && isalpha((unsigned char) *cp))
1764                 cp++;
1765
1766         if (DecodeTimezone(cp, &tz) != 0)
1767                 return -1;
1768
1769         delim = *cp;
1770         *cp = '\0';
1771         type = DecodeSpecial(MAXDATEFIELDS - 1, str, &val);
1772         *cp = delim;
1773
1774         switch (type)
1775         {
1776                 case DTZ:
1777                 case TZ:
1778                         *tzp = (val * 60) - tz;
1779                         break;
1780
1781                 default:
1782                         return -1;
1783         }
1784
1785         return 0;
1786 }       /* DecodePosixTimezone() */
1787
1788 /* ParseDateTime()
1789  * Break string into tokens based on a date/time context.
1790  * Several field types are assigned:
1791  *      DTK_NUMBER - digits and (possibly) a decimal point
1792  *      DTK_DATE - digits and two delimiters, or digits and text
1793  *      DTK_TIME - digits, colon delimiters, and possibly a decimal point
1794  *      DTK_STRING - text (no digits)
1795  *      DTK_SPECIAL - leading "+" or "-" followed by text
1796  *      DTK_TZ - leading "+" or "-" followed by digits
1797  * Note that some field types can hold unexpected items:
1798  *      DTK_NUMBER can hold date fields (yy.ddd)
1799  *      DTK_STRING can hold months (January) and time zones (PST)
1800  *      DTK_DATE can hold Posix time zones (GMT-8)
1801  */
1802 int
1803 ParseDateTime(char *timestr, char *lowstr,
1804   char **field, int *ftype, int maxfields, int *numfields, char **endstr)
1805 {
1806         int                     nf = 0;
1807         char       *lp = lowstr;
1808
1809         *endstr = timestr;
1810         /* outer loop through fields */
1811         while (*(*endstr) != '\0')
1812         {
1813                 field[nf] = lp;
1814
1815                 /* leading digit? then date or time */
1816                 if (isdigit((unsigned char) *(*endstr)))
1817                 {
1818                         *lp++ = *(*endstr)++;
1819                         while (isdigit((unsigned char) *(*endstr)))
1820                                 *lp++ = *(*endstr)++;
1821
1822                         /* time field? */
1823                         if (*(*endstr) == ':')
1824                         {
1825                                 ftype[nf] = DTK_TIME;
1826                                 *lp++ = *(*endstr)++;
1827                                 while (isdigit((unsigned char) *(*endstr)) ||
1828                                            (*(*endstr) == ':') || (*(*endstr) == '.'))
1829                                         *lp++ = *(*endstr)++;
1830                         }
1831                         /* date field? allow embedded text month */
1832                         else if ((*(*endstr) == '-') || (*(*endstr) == '/') || (*(*endstr) == '.'))
1833                         {
1834                                 /* save delimiting character to use later */
1835                                 char       *dp = (*endstr);
1836
1837                                 *lp++ = *(*endstr)++;
1838                                 /* second field is all digits? then no embedded text month */
1839                                 if (isdigit((unsigned char) *(*endstr)))
1840                                 {
1841                                         ftype[nf] = ((*dp == '.') ? DTK_NUMBER : DTK_DATE);
1842                                         while (isdigit((unsigned char) *(*endstr)))
1843                                                 *lp++ = *(*endstr)++;
1844
1845                                         /*
1846                                          * insist that the delimiters match to get a
1847                                          * three-field date.
1848                                          */
1849                                         if (*(*endstr) == *dp)
1850                                         {
1851                                                 ftype[nf] = DTK_DATE;
1852                                                 *lp++ = *(*endstr)++;
1853                                                 while (isdigit((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
1854                                                         *lp++ = *(*endstr)++;
1855                                         }
1856                                 }
1857                                 else
1858                                 {
1859                                         ftype[nf] = DTK_DATE;
1860                                         while (isalnum((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
1861                                                 *lp++ = tolower((unsigned char) *(*endstr)++);
1862                                 }
1863                         }
1864
1865                         /*
1866                          * otherwise, number only and will determine year, month, day,
1867                          * or concatenated fields later...
1868                          */
1869                         else
1870                                 ftype[nf] = DTK_NUMBER;
1871                 }
1872                 /* Leading decimal point? Then fractional seconds... */
1873                 else if (*(*endstr) == '.')
1874                 {
1875                         *lp++ = *(*endstr)++;
1876                         while (isdigit((unsigned char) *(*endstr)))
1877                                 *lp++ = *(*endstr)++;
1878
1879                         ftype[nf] = DTK_NUMBER;
1880                 }
1881
1882                 /*
1883                  * text? then date string, month, day of week, special, or
1884                  * timezone
1885                  */
1886                 else if (isalpha((unsigned char) *(*endstr)))
1887                 {
1888                         ftype[nf] = DTK_STRING;
1889                         *lp++ = tolower((unsigned char) *(*endstr)++);
1890                         while (isalpha((unsigned char) *(*endstr)))
1891                                 *lp++ = tolower((unsigned char) *(*endstr)++);
1892
1893                         /*
1894                          * Full date string with leading text month? Could also be a
1895                          * POSIX time zone...
1896                          */
1897                         if ((*(*endstr) == '-') || (*(*endstr) == '/') || (*(*endstr) == '.'))
1898                         {
1899                                 char       *dp = (*endstr);
1900
1901                                 ftype[nf] = DTK_DATE;
1902                                 *lp++ = *(*endstr)++;
1903                                 while (isdigit((unsigned char) *(*endstr)) || (*(*endstr) == *dp))
1904                                         *lp++ = *(*endstr)++;
1905                         }
1906                 }
1907                 /* skip leading spaces */
1908                 else if (isspace((unsigned char) *(*endstr)))
1909                 {
1910                         (*endstr)++;
1911                         continue;
1912                 }
1913                 /* sign? then special or numeric timezone */
1914                 else if ((*(*endstr) == '+') || (*(*endstr) == '-'))
1915                 {
1916                         *lp++ = *(*endstr)++;
1917                         /* soak up leading whitespace */
1918                         while (isspace((unsigned char) *(*endstr)))
1919                                 (*endstr)++;
1920                         /* numeric timezone? */
1921                         if (isdigit((unsigned char) *(*endstr)))
1922                         {
1923                                 ftype[nf] = DTK_TZ;
1924                                 *lp++ = *(*endstr)++;
1925                                 while (isdigit((unsigned char) *(*endstr)) ||
1926                                            (*(*endstr) == ':') || (*(*endstr) == '.'))
1927                                         *lp++ = *(*endstr)++;
1928                         }
1929                         /* special? */
1930                         else if (isalpha((unsigned char) *(*endstr)))
1931                         {
1932                                 ftype[nf] = DTK_SPECIAL;
1933                                 *lp++ = tolower((unsigned char) *(*endstr)++);
1934                                 while (isalpha((unsigned char) *(*endstr)))
1935                                         *lp++ = tolower((unsigned char) *(*endstr)++);
1936                         }
1937                         /* otherwise something wrong... */
1938                         else
1939                                 return -1;
1940                 }
1941                 /* ignore punctuation but use as delimiter */
1942                 else if (ispunct((unsigned char) *(*endstr)))
1943                 {
1944                         (*endstr)++;
1945                         continue;
1946
1947                 }
1948                 /* otherwise, something is not right... */
1949                 else
1950                         return -1;
1951
1952                 /* force in a delimiter after each field */
1953                 *lp++ = '\0';
1954                 nf++;
1955                 if (nf > MAXDATEFIELDS)
1956                         return -1;
1957         }
1958
1959         *numfields = nf;
1960
1961         return 0;
1962 }       /* ParseDateTime() */
1963
1964
1965 /* DecodeDateTime()
1966  * Interpret previously parsed fields for general date and time.
1967  * Return 0 if full date, 1 if only time, and -1 if problems.
1968  *              External format(s):
1969  *                              "<weekday> <month>-<day>-<year> <hour>:<minute>:<second>"
1970  *                              "Fri Feb-7-1997 15:23:27"
1971  *                              "Feb-7-1997 15:23:27"
1972  *                              "2-7-1997 15:23:27"
1973  *                              "1997-2-7 15:23:27"
1974  *                              "1997.038 15:23:27"             (day of year 1-366)
1975  *              Also supports input in compact time:
1976  *                              "970207 152327"
1977  *                              "97038 152327"
1978  *                              "20011225T040506.789-07"
1979  *
1980  * Use the system-provided functions to get the current time zone
1981  *      if not specified in the input string.
1982  * If the date is outside the time_t system-supported time range,
1983  *      then assume UTC time zone. - thomas 1997-05-27
1984  */
1985 int
1986 DecodeDateTime(char **field, int *ftype, int nf,
1987           int *dtype, struct tm * tm, fsec_t *fsec, int *tzp, bool EuroDates)
1988 {
1989         int                     fmask = 0,
1990                                 tmask,
1991                                 type;
1992         int                     ptype = 0;              /* "prefix type" for ISO y2001m02d04
1993                                                                  * format */
1994         int                     i;
1995         int                     val;
1996         int                     mer = HR24;
1997         int                     haveTextMonth = FALSE;
1998         int                     is2digits = FALSE;
1999         int                     bc = FALSE;
2000
2001         /***
2002          * We'll insist on at least all of the date fields, but initialize the
2003          * remaining fields in case they are not set later...
2004          ***/
2005         *dtype = DTK_DATE;
2006         tm->tm_hour = 0;
2007         tm->tm_min = 0;
2008         tm->tm_sec = 0;
2009         *fsec = 0;
2010         /* don't know daylight savings time status apriori */
2011         tm->tm_isdst = -1;
2012         if (tzp != NULL)
2013                 *tzp = 0;
2014
2015         for (i = 0; i < nf; i++)
2016         {
2017                 switch (ftype[i])
2018                 {
2019                         case DTK_DATE:
2020                                 /***
2021                                  * Integral julian day with attached time zone?
2022                                  * All other forms with JD will be separated into
2023                                  * distinct fields, so we handle just this case here.
2024                                  ***/
2025                                 if (ptype == DTK_JULIAN)
2026                                 {
2027                                         char       *cp;
2028                                         int                     val;
2029
2030                                         if (tzp == NULL)
2031                                                 return -1;
2032
2033                                         val = strtol(field[i], &cp, 10);
2034                                         if (*cp != '-')
2035                                                 return -1;
2036
2037                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2038                                         /* Get the time zone from the end of the string */
2039                                         if (DecodeTimezone(cp, tzp) != 0)
2040                                                 return -1;
2041
2042                                         tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
2043                                         ptype = 0;
2044                                         break;
2045                                 }
2046                                 /***
2047                                  * Already have a date? Then this might be a POSIX time
2048                                  * zone with an embedded dash (e.g. "PST-3" == "EST") or
2049                                  * a run-together time with trailing time zone (e.g. hhmmss-zz).
2050                                  * - thomas 2001-12-25
2051                                  ***/
2052                                 else if (((fmask & DTK_DATE_M) == DTK_DATE_M)
2053                                                  || (ptype != 0))
2054                                 {
2055                                         /* No time zone accepted? Then quit... */
2056                                         if (tzp == NULL)
2057                                                 return -1;
2058
2059                                         if (isdigit((unsigned char) *field[i]) || ptype != 0)
2060                                         {
2061                                                 char       *cp;
2062
2063                                                 if (ptype != 0)
2064                                                 {
2065                                                         /* Sanity check; should not fail this test */
2066                                                         if (ptype != DTK_TIME)
2067                                                                 return -1;
2068                                                         ptype = 0;
2069                                                 }
2070
2071                                                 /*
2072                                                  * Starts with a digit but we already have a time
2073                                                  * field? Then we are in trouble with a date and
2074                                                  * time already...
2075                                                  */
2076                                                 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
2077                                                         return -1;
2078
2079                                                 if ((cp = strchr(field[i], '-')) == NULL)
2080                                                         return -1;
2081
2082                                                 /* Get the time zone from the end of the string */
2083                                                 if (DecodeTimezone(cp, tzp) != 0)
2084                                                         return -1;
2085                                                 *cp = '\0';
2086
2087                                                 /*
2088                                                  * Then read the rest of the field as a
2089                                                  * concatenated time
2090                                                  */
2091                                                 if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], fmask,
2092                                                    &tmask, tm, fsec, &is2digits, EuroDates)) < 0)
2093                                                         return -1;
2094
2095                                                 /*
2096                                                  * modify tmask after returning from
2097                                                  * DecodeNumberField()
2098                                                  */
2099                                                 tmask |= DTK_M(TZ);
2100                                         }
2101                                         else
2102                                         {
2103                                                 if (DecodePosixTimezone(field[i], tzp) != 0)
2104                                                         return -1;
2105
2106                                                 ftype[i] = DTK_TZ;
2107                                                 tmask = DTK_M(TZ);
2108                                         }
2109                                 }
2110                                 else if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
2111                                         return -1;
2112                                 break;
2113
2114                         case DTK_TIME:
2115                                 if (DecodeTime(field[i], fmask, &tmask, tm, fsec) != 0)
2116                                         return -1;
2117
2118                                 /*
2119                                  * Check upper limit on hours; other limits checked in
2120                                  * DecodeTime()
2121                                  */
2122                                 if (tm->tm_hour > 23)
2123                                         return -1;
2124                                 break;
2125
2126                         case DTK_TZ:
2127                                 {
2128                                         int                     tz;
2129
2130                                         if (tzp == NULL)
2131                                                 return -1;
2132
2133                                         if (DecodeTimezone(field[i], &tz) != 0)
2134                                                 return -1;
2135
2136                                         /*
2137                                          * Already have a time zone? Then maybe this is the
2138                                          * second field of a POSIX time: EST+3 (equivalent to
2139                                          * PST)
2140                                          */
2141                                         if ((i > 0) && ((fmask & DTK_M(TZ)) != 0)
2142                                                 && (ftype[i - 1] == DTK_TZ)
2143                                                 && (isalpha((unsigned char) *field[i - 1])))
2144                                         {
2145                                                 *tzp -= tz;
2146                                                 tmask = 0;
2147                                         }
2148                                         else
2149                                         {
2150                                                 *tzp = tz;
2151                                                 tmask = DTK_M(TZ);
2152                                         }
2153                                 }
2154                                 break;
2155
2156                         case DTK_NUMBER:
2157
2158                                 /*
2159                                  * Was this an "ISO date" with embedded field labels? An
2160                                  * example is "y2001m02d04" - thomas 2001-02-04
2161                                  */
2162                                 if (ptype != 0)
2163                                 {
2164                                         char       *cp;
2165                                         int                     val;
2166
2167                                         val = strtol(field[i], &cp, 10);
2168
2169                                         /*
2170                                          * only a few kinds are allowed to have an embedded
2171                                          * decimal
2172                                          */
2173                                         if (*cp == '.')
2174                                                 switch (ptype)
2175                                                 {
2176                                                         case DTK_JULIAN:
2177                                                         case DTK_TIME:
2178                                                         case DTK_SECOND:
2179                                                                 break;
2180                                                         default:
2181                                                                 return 1;
2182                                                                 break;
2183                                                 }
2184                                         else if (*cp != '\0')
2185                                                 return -1;
2186
2187                                         switch (ptype)
2188                                         {
2189                                                 case DTK_YEAR:
2190                                                         tm->tm_year = val;
2191                                                         tmask = DTK_M(YEAR);
2192                                                         break;
2193
2194                                                 case DTK_MONTH:
2195
2196                                                         /*
2197                                                          * already have a month and hour? then assume
2198                                                          * minutes
2199                                                          */
2200                                                         if (((fmask & DTK_M(MONTH)) != 0)
2201                                                                 && ((fmask & DTK_M(HOUR)) != 0))
2202                                                         {
2203                                                                 tm->tm_min = val;
2204                                                                 tmask = DTK_M(MINUTE);
2205                                                         }
2206                                                         else
2207                                                         {
2208                                                                 tm->tm_mon = val;
2209                                                                 tmask = DTK_M(MONTH);
2210                                                         }
2211                                                         break;
2212
2213                                                 case DTK_DAY:
2214                                                         tm->tm_mday = val;
2215                                                         tmask = DTK_M(DAY);
2216                                                         break;
2217
2218                                                 case DTK_HOUR:
2219                                                         tm->tm_hour = val;
2220                                                         tmask = DTK_M(HOUR);
2221                                                         break;
2222
2223                                                 case DTK_MINUTE:
2224                                                         tm->tm_min = val;
2225                                                         tmask = DTK_M(MINUTE);
2226                                                         break;
2227
2228                                                 case DTK_SECOND:
2229                                                         tm->tm_sec = val;
2230                                                         tmask = DTK_M(SECOND);
2231                                                         if (*cp == '.')
2232                                                         {
2233                                                                 double          frac;
2234
2235                                                                 frac = strtod(cp, &cp);
2236                                                                 if (*cp != '\0')
2237                                                                         return -1;
2238 #ifdef HAVE_INT64_TIMESTAMP
2239                                                                 *fsec = frac * 1000000;
2240 #else
2241                                                                 *fsec = frac;
2242 #endif
2243                                                         }
2244                                                         break;
2245
2246                                                 case DTK_TZ:
2247                                                         tmask = DTK_M(TZ);
2248                                                         if (DecodeTimezone(field[i], tzp) != 0)
2249                                                                 return -1;
2250                                                         break;
2251
2252                                                 case DTK_JULIAN:
2253                                                         /***
2254                                                          * previous field was a label for "julian date"?
2255                                                          ***/
2256                                                         tmask = DTK_DATE_M;
2257                                                         j2date(val, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2258                                                         /* fractional Julian Day? */
2259                                                         if (*cp == '.')
2260                                                         {
2261                                                                 double          time;
2262
2263                                                                 time = strtod(cp, &cp);
2264                                                                 if (*cp != '\0')
2265                                                                         return -1;
2266
2267                                                                 tmask |= DTK_TIME_M;
2268 #ifdef HAVE_INT64_TIMESTAMP
2269                                                                 dt2time((time * 86400000000), &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
2270 #else
2271                                                                 dt2time((time * 86400), &tm->tm_hour, &tm->tm_min, &tm->tm_sec, fsec);
2272 #endif
2273                                                         }
2274                                                         break;
2275
2276                                                 case DTK_TIME:
2277                                                         /* previous field was "t" for ISO time */
2278                                                         if ((ftype[i] = DecodeNumberField(strlen(field[i]), field[i], (fmask | DTK_DATE_M),
2279                                                         &tmask, tm, fsec, &is2digits, EuroDates)) < 0)
2280                                                                 return -1;
2281
2282                                                         if (tmask != DTK_TIME_M)
2283                                                                 return -1;
2284                                                         break;
2285
2286                                                 default:
2287                                                         return -1;
2288                                                         break;
2289                                         }
2290
2291                                         ptype = 0;
2292                                         *dtype = DTK_DATE;
2293                                 }
2294                                 else
2295                                 {
2296                                         char       *cp;
2297                                         int                     flen;
2298
2299                                         flen = strlen(field[i]);
2300                                         cp = strchr(field[i], '.');
2301
2302                                         /* Embedded decimal and no date yet? */
2303                                         if ((cp != NULL) && !(fmask & DTK_DATE_M))
2304                                         {
2305                                                 if (DecodeDate(field[i], fmask, &tmask, tm, EuroDates) != 0)
2306                                                         return -1;
2307                                         }
2308                                         /* embedded decimal and several digits before? */
2309                                         else if ((cp != NULL) && ((flen - strlen(cp)) > 2))
2310                                         {
2311                                                 /*
2312                                                  * Interpret as a concatenated date or time Set
2313                                                  * the type field to allow decoding other fields
2314                                                  * later. Example: 20011223 or 040506
2315                                                  */
2316                                                 if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
2317                                                    &tmask, tm, fsec, &is2digits, EuroDates)) < 0)
2318                                                         return -1;
2319                                         }
2320                                         else if (flen > 4)
2321                                         {
2322                                                 if ((ftype[i] = DecodeNumberField(flen, field[i], fmask,
2323                                                    &tmask, tm, fsec, &is2digits, EuroDates)) < 0)
2324                                                         return -1;
2325                                         }
2326                                         /* otherwise it is a single date/time field... */
2327                                         else if (DecodeNumber(flen, field[i], fmask,
2328                                                    &tmask, tm, fsec, &is2digits, EuroDates) != 0)
2329                                                 return -1;
2330                                 }
2331                                 break;
2332
2333                         case DTK_STRING:
2334                         case DTK_SPECIAL:
2335                                 type = DecodeSpecial(i, field[i], &val);
2336                                 if (type == IGNORE_DTF)
2337                                         continue;
2338
2339                                 tmask = DTK_M(type);
2340                                 switch (type)
2341                                 {
2342                                         case RESERV:
2343                                                 switch (val)
2344                                                 {
2345                                                         case DTK_NOW:
2346                                                                 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
2347                                                                 *dtype = DTK_DATE;
2348                                                                 GetCurrentDateTime(tm);
2349                                                                 break;
2350
2351                                                         case DTK_YESTERDAY:
2352                                                                 tmask = DTK_DATE_M;
2353                                                                 *dtype = DTK_DATE;
2354                                                                 GetCurrentDateTime(tm);
2355                                                                 j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) - 1),
2356                                                                 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2357                                                                 tm->tm_hour = 0;
2358                                                                 tm->tm_min = 0;
2359                                                                 tm->tm_sec = 0;
2360                                                                 break;
2361
2362                                                         case DTK_TODAY:
2363                                                                 tmask = DTK_DATE_M;
2364                                                                 *dtype = DTK_DATE;
2365                                                                 GetCurrentDateTime(tm);
2366                                                                 tm->tm_hour = 0;
2367                                                                 tm->tm_min = 0;
2368                                                                 tm->tm_sec = 0;
2369                                                                 break;
2370
2371                                                         case DTK_TOMORROW:
2372                                                                 tmask = DTK_DATE_M;
2373                                                                 *dtype = DTK_DATE;
2374                                                                 GetCurrentDateTime(tm);
2375                                                                 j2date((date2j(tm->tm_year, tm->tm_mon, tm->tm_mday) + 1),
2376                                                                 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2377                                                                 tm->tm_hour = 0;
2378                                                                 tm->tm_min = 0;
2379                                                                 tm->tm_sec = 0;
2380                                                                 break;
2381
2382                                                         case DTK_ZULU:
2383                                                                 tmask = (DTK_TIME_M | DTK_M(TZ));
2384                                                                 *dtype = DTK_DATE;
2385                                                                 tm->tm_hour = 0;
2386                                                                 tm->tm_min = 0;
2387                                                                 tm->tm_sec = 0;
2388                                                                 if (tzp != NULL)
2389                                                                         *tzp = 0;
2390                                                                 break;
2391
2392                                                         default:
2393                                                                 *dtype = val;
2394                                                 }
2395
2396                                                 break;
2397
2398                                         case MONTH:
2399
2400                                                 /*
2401                                                  * already have a (numeric) month? then see if we
2402                                                  * can substitute...
2403                                                  */
2404                                                 if ((fmask & DTK_M(MONTH)) && (!haveTextMonth)
2405                                                         && (!(fmask & DTK_M(DAY)))
2406                                                         && ((tm->tm_mon >= 1) && (tm->tm_mon <= 31)))
2407                                                 {
2408                                                         tm->tm_mday = tm->tm_mon;
2409                                                         tmask = DTK_M(DAY);
2410                                                 }
2411                                                 haveTextMonth = TRUE;
2412                                                 tm->tm_mon = val;
2413                                                 break;
2414
2415                                         case DTZMOD:
2416
2417                                                 /*
2418                                                  * daylight savings time modifier (solves "MET
2419                                                  * DST" syntax)
2420                                                  */
2421                                                 tmask |= DTK_M(DTZ);
2422                                                 tm->tm_isdst = 1;
2423                                                 if (tzp == NULL)
2424                                                         return -1;
2425                                                 *tzp += val * 60;
2426                                                 break;
2427
2428                                         case DTZ:
2429
2430                                                 /*
2431                                                  * set mask for TZ here _or_ check for DTZ later
2432                                                  * when getting default timezone
2433                                                  */
2434                                                 tmask |= DTK_M(TZ);
2435                                                 tm->tm_isdst = 1;
2436                                                 if (tzp == NULL)
2437                                                         return -1;
2438                                                 *tzp = val * 60;
2439                                                 ftype[i] = DTK_TZ;
2440                                                 break;
2441
2442                                         case TZ:
2443                                                 tm->tm_isdst = 0;
2444                                                 if (tzp == NULL)
2445                                                         return -1;
2446                                                 *tzp = val * 60;
2447                                                 ftype[i] = DTK_TZ;
2448                                                 break;
2449
2450                                         case IGNORE_DTF:
2451                                                 break;
2452
2453                                         case AMPM:
2454                                                 mer = val;
2455                                                 break;
2456
2457                                         case ADBC:
2458                                                 bc = (val == BC);
2459                                                 break;
2460
2461                                         case DOW:
2462                                                 tm->tm_wday = val;
2463                                                 break;
2464
2465                                         case UNITS:
2466                                                 tmask = 0;
2467                                                 ptype = val;
2468                                                 break;
2469
2470                                         case ISOTIME:
2471
2472                                                 /*
2473                                                  * This is a filler field "t" indicating that the
2474                                                  * next field is time. Try to verify that this is
2475                                                  * sensible.
2476                                                  */
2477                                                 tmask = 0;
2478
2479                                                 /* No preceeding date? Then quit... */
2480                                                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2481                                                         return -1;
2482
2483                                                 /***
2484                                                  * We will need one of the following fields:
2485                                                  *      DTK_NUMBER should be hhmmss.fff
2486                                                  *      DTK_TIME should be hh:mm:ss.fff
2487                                                  *      DTK_DATE should be hhmmss-zz
2488                                                  ***/
2489                                                 if ((i >= (nf - 1))
2490                                                         || ((ftype[i + 1] != DTK_NUMBER)
2491                                                                 && (ftype[i + 1] != DTK_TIME)
2492                                                                 && (ftype[i + 1] != DTK_DATE)))
2493                                                         return -1;
2494
2495                                                 ptype = val;
2496                                                 break;
2497
2498                                         default:
2499                                                 return -1;
2500                                 }
2501                                 break;
2502
2503                         default:
2504                                 return -1;
2505                 }
2506
2507                 if (tmask & fmask)
2508                         return -1;
2509                 fmask |= tmask;
2510         }
2511
2512         /* there is no year zero in AD/BC notation; i.e. "1 BC" == year 0 */
2513         if (bc)
2514         {
2515                 if (tm->tm_year > 0)
2516                         tm->tm_year = -(tm->tm_year - 1);
2517                 else
2518                         return -1;
2519         }
2520         else if (is2digits)
2521         {
2522                 if (tm->tm_year < 70)
2523                         tm->tm_year += 2000;
2524                 else if (tm->tm_year < 100)
2525                         tm->tm_year += 1900;
2526         }
2527
2528         if ((mer != HR24) && (tm->tm_hour > 12))
2529                 return -1;
2530         if ((mer == AM) && (tm->tm_hour == 12))
2531                 tm->tm_hour = 0;
2532         else if ((mer == PM) && (tm->tm_hour != 12))
2533                 tm->tm_hour += 12;
2534
2535         /* do additional checking for full date specs... */
2536         if (*dtype == DTK_DATE)
2537         {
2538                 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2539                         return ((fmask & DTK_TIME_M) == DTK_TIME_M) ? 1 : -1;
2540
2541                 /*
2542                  * check for valid day of month, now that we know for sure the
2543                  * month and year...
2544                  */
2545                 if ((tm->tm_mday < 1)
2546                  || (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1]))
2547                         return -1;
2548
2549                 /* timezone not specified? then find local timezone if possible */
2550                 if (((fmask & DTK_DATE_M) == DTK_DATE_M)
2551                         && (tzp != NULL) && (!(fmask & DTK_M(TZ))))
2552                 {
2553                         /*
2554                          * daylight savings time modifier but no standard timezone?
2555                          * then error
2556                          */
2557                         if (fmask & DTK_M(DTZMOD))
2558                                 return -1;
2559
2560                         *tzp = DetermineLocalTimeZone(tm);
2561                 }
2562         }
2563
2564         return 0;
2565 }       /* DecodeDateTime() */
2566
2567 /* Function works as follows:
2568  *
2569  *
2570  * */
2571
2572 static char *
2573 find_end_token(char *str, char *fmt)
2574 {
2575         /*
2576          * str: here is28the day12the hour fmt: here is%dthe day%hthe hour
2577          *
2578          * we extract the 28, we read the percent sign and the type "d" then this
2579          * functions gets called as find_end_token("28the day12the hour", "the
2580          * day%hthehour")
2581          *
2582          * fmt points to "the day%hthehour", next_percent points to %hthehour and
2583          * we have to find a match for everything between these positions
2584          * ("the day"). We look for "the day" in str and know that the pattern
2585          * we are about to scan ends where this string starts (right after the
2586          * "28")
2587          *
2588          * At the end, *fmt is '\0' and *str isn't. end_position then is
2589          * unchanged.
2590          */
2591         char       *end_position = NULL;
2592         char       *next_percent,
2593                            *subst_location = NULL;
2594         int                     scan_offset = 0;
2595         char            last_char;
2596
2597         /* are we at the end? */
2598         if (!*fmt)
2599         {
2600                 end_position = fmt;
2601                 return end_position;
2602         }
2603
2604         /* not at the end */
2605         while (fmt[scan_offset] == '%' && fmt[scan_offset + 1])
2606         {
2607                 /*
2608                  * there is no delimiter, skip to the next delimiter if we're
2609                  * reading a number and then something that is not a number
2610                  * "9:15pm", we might be able to recover with the strtol end
2611                  * pointer. Go for the next percent sign
2612                  */
2613                 scan_offset += 2;
2614         }
2615         next_percent = strchr(fmt + scan_offset, '%');
2616         if (next_percent)
2617         {
2618                 /*
2619                  * we don't want to allocate extra memory, so we temporarily set
2620                  * the '%' sign to '\0' and call strstr However since we allow
2621                  * whitespace to float around everything, we have to shorten the
2622                  * pattern until we reach a non-whitespace character
2623                  */
2624
2625                 subst_location = next_percent;
2626                 while (*(subst_location - 1) == ' ' && subst_location - 1 > fmt + scan_offset)
2627                         subst_location--;
2628                 last_char = *subst_location;
2629                 *subst_location = '\0';
2630
2631                 /*
2632                  * the haystack is the str and the needle is the original fmt but
2633                  * it ends at the position where the next percent sign would be
2634                  */
2635
2636                 /*
2637                  * There is one special case. Imagine: str = " 2", fmt = "%d
2638                  * %...", since we want to allow blanks as "dynamic" padding we
2639                  * have to accept this. Now, we are called with a fmt of " %..."
2640                  * and look for " " in str. We find it at the first position and
2641                  * never read the 2...
2642                  */
2643                 while (*str == ' ')
2644                         str++;
2645                 end_position = strstr(str, fmt + scan_offset);
2646                 *subst_location = last_char;
2647         }
2648         else
2649         {
2650                 /*
2651                  * there is no other percent sign. So everything up to the end has
2652                  * to match.
2653                  */
2654                 end_position = str + strlen(str);
2655         }
2656         if (!end_position)
2657         {
2658                 /*
2659                  * maybe we have the following case:
2660                  *
2661                  * str = "4:15am" fmt = "%M:%S %p"
2662                  *
2663                  * at this place we could have
2664                  *
2665                  * str = "15am" fmt = " %p"
2666                  *
2667                  * and have set fmt to " " because overwrote the % sign with a NULL
2668                  *
2669                  * In this case where we would have to match a space but can't find
2670                  * it, set end_position to the end of the string
2671                  */
2672                 if ((fmt + scan_offset)[0] == ' ' && fmt + scan_offset + 1 == subst_location)
2673                         end_position = str + strlen(str);
2674         }
2675         return end_position;
2676 }
2677
2678 static int
2679 pgtypes_defmt_scan(union un_fmt_comb * scan_val, int scan_type, char **pstr, char *pfmt)
2680 {
2681         /*
2682          * scan everything between pstr and pstr_end. This is not including
2683          * the last character so we might set it to '\0' for the parsing
2684          */
2685
2686         char            last_char;
2687         int                     err = 0;
2688         char       *pstr_end;
2689         char       *strtol_end = NULL;
2690
2691         while (**pstr == ' ')
2692                 pstr++;
2693         pstr_end = find_end_token(*pstr, pfmt);
2694         if (!pstr_end)
2695         {
2696                 /* there was an error, no match */
2697                 err = 1;
2698                 return err;
2699         }
2700         last_char = *pstr_end;
2701         *pstr_end = '\0';
2702
2703         switch (scan_type)
2704         {
2705                 case PGTYPES_TYPE_UINT:
2706
2707                         /*
2708                          * numbers may be blank-padded, this is the only deviation
2709                          * from the fmt-string we accept
2710                          */
2711                         while (**pstr == ' ')
2712                                 (*pstr)++;
2713                         errno = 0;
2714                         scan_val->uint_val = (unsigned int) strtol(*pstr, &strtol_end, 10);
2715                         if (errno)
2716                                 err = 1;
2717                         break;
2718                 case PGTYPES_TYPE_UINT_LONG:
2719                         while (**pstr == ' ')
2720                                 (*pstr)++;
2721                         errno = 0;
2722                         scan_val->uint_val = (unsigned long int) strtol(*pstr, &strtol_end, 10);
2723                         if (errno)
2724                                 err = 1;
2725                         break;
2726                 case PGTYPES_TYPE_STRING_MALLOCED:
2727                         if (pstr)
2728                                 scan_val->str_val = pgtypes_strdup(*pstr);
2729         }
2730         if (strtol_end && *strtol_end)
2731                 *pstr = strtol_end;
2732         else
2733                 *pstr = pstr_end;
2734         *pstr_end = last_char;
2735         return err;
2736 }
2737
2738 /* XXX range checking */
2739 int PGTYPEStimestamp_defmt_scan(char **, char *, timestamp *, int *, int *, int *,
2740                                                         int *, int *, int *, int *);
2741
2742 int
2743 PGTYPEStimestamp_defmt_scan(char **str, char *fmt, timestamp *d,
2744                                                         int *year, int *month, int *day,
2745                                                         int *hour, int *minute, int *second,
2746                                                         int *tz)
2747 {
2748         union un_fmt_comb scan_val;
2749         int                     scan_type;
2750
2751         char       *pstr,
2752                            *pfmt,
2753                            *tmp;
2754         int                     err = 1;
2755         int                     j;
2756         struct tm       tm;
2757
2758         pfmt = fmt;
2759         pstr = *str;
2760
2761         while (*pfmt)
2762         {
2763                 err = 0;
2764                 while (*pfmt == ' ')
2765                         pfmt++;
2766                 while (*pstr == ' ')
2767                         pstr++;
2768                 if (*pfmt != '%')
2769                 {
2770                         if (*pfmt == *pstr)
2771                         {
2772                                 pfmt++;
2773                                 pstr++;
2774                         }
2775                         else
2776                         {
2777                                 /* XXX Error: no match */
2778                                 err = 1;
2779                                 return err;
2780                         }
2781                         continue;
2782                 }
2783                 /* here *pfmt equals '%' */
2784                 pfmt++;
2785                 switch (*pfmt)
2786                 {
2787                         case 'a':
2788                                 pfmt++;
2789
2790                                 /*
2791                                  * we parse the day and see if it is a week day but we do
2792                                  * not check if the week day really matches the date
2793                                  */
2794                                 err = 1;
2795                                 j = 0;
2796                                 while (pgtypes_date_weekdays_short[j])
2797                                 {
2798                                         if (strncmp(pgtypes_date_weekdays_short[j], pstr,
2799                                                         strlen(pgtypes_date_weekdays_short[j])) == 0)
2800                                         {
2801                                                 /* found it */
2802                                                 err = 0;
2803                                                 pstr += strlen(pgtypes_date_weekdays_short[j]);
2804                                                 break;
2805                                         }
2806                                         j++;
2807                                 }
2808                                 break;
2809                         case 'A':
2810                                 /* see note above */
2811                                 pfmt++;
2812                                 err = 1;
2813                                 j = 0;
2814                                 while (days[j])
2815                                 {
2816                                         if (strncmp(days[j], pstr, strlen(days[j])) == 0)
2817                                         {
2818                                                 /* found it */
2819                                                 err = 0;
2820                                                 pstr += strlen(days[j]);
2821                                                 break;
2822                                         }
2823                                         j++;
2824                                 }
2825                                 break;
2826                         case 'b':
2827                         case 'h':
2828                                 pfmt++;
2829                                 err = 1;
2830                                 j = 0;
2831                                 while (months[j])
2832                                 {
2833                                         if (strncmp(months[j], pstr, strlen(months[j])) == 0)
2834                                         {
2835                                                 /* found it */
2836                                                 err = 0;
2837                                                 pstr += strlen(months[j]);
2838                                                 *month = j + 1;
2839                                                 break;
2840                                         }
2841                                         j++;
2842                                 }
2843                                 break;
2844                         case 'B':
2845                                 /* see note above */
2846                                 pfmt++;
2847                                 err = 1;
2848                                 j = 0;
2849                                 while (pgtypes_date_months[j])
2850                                 {
2851                                         if (strncmp(pgtypes_date_months[j], pstr, strlen(pgtypes_date_months[j])) == 0)
2852                                         {
2853                                                 /* found it */
2854                                                 err = 0;
2855                                                 pstr += strlen(pgtypes_date_months[j]);
2856                                                 *month = j + 1;
2857                                                 break;
2858                                         }
2859                                         j++;
2860                                 }
2861                                 break;
2862                         case 'c':
2863                                 /* XXX */
2864                                 break;
2865                         case 'C':
2866                                 pfmt++;
2867                                 scan_type = PGTYPES_TYPE_UINT;
2868                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2869                                 *year = scan_val.uint_val * 100;
2870                                 break;
2871                         case 'd':
2872                         case 'e':
2873                                 pfmt++;
2874                                 scan_type = PGTYPES_TYPE_UINT;
2875                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2876                                 *day = scan_val.uint_val;
2877                                 break;
2878                         case 'D':
2879
2880                                 /*
2881                                  * we have to concatenate the strings in order to be able
2882                                  * to find the end of the substitution
2883                                  */
2884                                 pfmt++;
2885                                 tmp = pgtypes_alloc(strlen("%m/%d/%y") + strlen(pstr) + 1);
2886                                 strcpy(tmp, "%m/%d/%y");
2887                                 strcat(tmp, pfmt);
2888                                 err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
2889                                 free(tmp);
2890                                 return err;
2891                         case 'm':
2892                                 pfmt++;
2893                                 scan_type = PGTYPES_TYPE_UINT;
2894                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2895                                 *month = scan_val.uint_val;
2896                                 break;
2897                         case 'y':
2898                         case 'g':                       /* XXX difference to y (ISO) */
2899                                 pfmt++;
2900                                 scan_type = PGTYPES_TYPE_UINT;
2901                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2902                                 if (*year < 0)
2903                                 {
2904                                         /* not yet set */
2905                                         *year = scan_val.uint_val;
2906                                 }
2907                                 else
2908                                         *year += scan_val.uint_val;
2909                                 if (*year < 100)
2910                                         *year += 1900;
2911                                 break;
2912                         case 'G':
2913                                 /* XXX difference to %V (ISO) */
2914                                 pfmt++;
2915                                 scan_type = PGTYPES_TYPE_UINT;
2916                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2917                                 *year = scan_val.uint_val;
2918                                 break;
2919                         case 'H':
2920                         case 'I':
2921                         case 'k':
2922                         case 'l':
2923                                 pfmt++;
2924                                 scan_type = PGTYPES_TYPE_UINT;
2925                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2926                                 *hour += scan_val.uint_val;
2927                                 break;
2928                         case 'j':
2929                                 pfmt++;
2930                                 scan_type = PGTYPES_TYPE_UINT;
2931                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2932
2933                                 /*
2934                                  * XXX what should we do with that? We could say that it's
2935                                  * sufficient if we have the year and the day within the
2936                                  * year to get at least a specific day.
2937                                  */
2938                                 break;
2939                         case 'M':
2940                                 pfmt++;
2941                                 scan_type = PGTYPES_TYPE_UINT;
2942                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
2943                                 *minute = scan_val.uint_val;
2944                                 break;
2945                         case 'n':
2946                                 pfmt++;
2947                                 if (*pstr == '\n')
2948                                         pstr++;
2949                                 else
2950                                         err = 1;
2951                                 break;
2952                         case 'p':
2953                                 err = 1;
2954                                 pfmt++;
2955                                 if (strncmp(pstr, "am", 2) == 0)
2956                                 {
2957                                         *hour += 0;
2958                                         err = 0;
2959                                         pstr += 2;
2960                                 }
2961                                 if (strncmp(pstr, "a.m.", 4) == 0)
2962                                 {
2963                                         *hour += 0;
2964                                         err = 0;
2965                                         pstr += 4;
2966                                 }
2967                                 if (strncmp(pstr, "pm", 2) == 0)
2968                                 {
2969                                         *hour += 12;
2970                                         err = 0;
2971                                         pstr += 2;
2972                                 }
2973                                 if (strncmp(pstr, "p.m.", 4) == 0)
2974                                 {
2975                                         *hour += 12;
2976                                         err = 0;
2977                                         pstr += 4;
2978                                 }
2979                                 break;
2980                         case 'P':
2981                                 err = 1;
2982                                 pfmt++;
2983                                 if (strncmp(pstr, "AM", 2) == 0)
2984                                 {
2985                                         *hour += 0;
2986                                         err = 0;
2987                                         pstr += 2;
2988                                 }
2989                                 if (strncmp(pstr, "A.M.", 4) == 0)
2990                                 {
2991                                         *hour += 0;
2992                                         err = 0;
2993                                         pstr += 4;
2994                                 }
2995                                 if (strncmp(pstr, "PM", 2) == 0)
2996                                 {
2997                                         *hour += 12;
2998                                         err = 0;
2999                                         pstr += 2;
3000                                 }
3001                                 if (strncmp(pstr, "P.M.", 4) == 0)
3002                                 {
3003                                         *hour += 12;
3004                                         err = 0;
3005                                         pstr += 4;
3006                                 }
3007                                 break;
3008                         case 'r':
3009                                 pfmt++;
3010                                 tmp = pgtypes_alloc(strlen("%I:%M:%S %p") + strlen(pstr) + 1);
3011                                 strcpy(tmp, "%I:%M:%S %p");
3012                                 strcat(tmp, pfmt);
3013                                 err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
3014                                 free(tmp);
3015                                 return err;
3016                         case 'R':
3017                                 pfmt++;
3018                                 tmp = pgtypes_alloc(strlen("%H:%M") + strlen(pstr) + 1);
3019                                 strcpy(tmp, "%H:%M");
3020                                 strcat(tmp, pfmt);
3021                                 err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
3022                                 free(tmp);
3023                                 return err;
3024                         case 's':
3025                                 pfmt++;
3026                                 scan_type = PGTYPES_TYPE_UINT_LONG;
3027                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3028                                 /* number of seconds in scan_val.luint_val */
3029                                 {
3030                                         struct tm  *tms;
3031                                         time_t          et = (time_t) scan_val.luint_val;
3032
3033                                         tms = gmtime(&et);
3034                                         *year = tms->tm_year;
3035                                         *month = tms->tm_mon;
3036                                         *day = tms->tm_mday;
3037                                         *hour = tms->tm_hour;
3038                                         *minute = tms->tm_min;
3039                                         *second = tms->tm_sec;
3040                                 }
3041                                 break;
3042                         case 'S':
3043                                 pfmt++;
3044                                 scan_type = PGTYPES_TYPE_UINT;
3045                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3046                                 *second = scan_val.uint_val;
3047                                 break;
3048                         case 't':
3049                                 pfmt++;
3050                                 if (*pstr == '\t')
3051                                         pstr++;
3052                                 else
3053                                         err = 1;
3054                                 break;
3055                         case 'T':
3056                                 pfmt++;
3057                                 tmp = pgtypes_alloc(strlen("%H:%M:%S") + strlen(pstr) + 1);
3058                                 strcpy(tmp, "%H:%M:%S");
3059                                 strcat(tmp, pfmt);
3060                                 err = PGTYPEStimestamp_defmt_scan(&pstr, tmp, d, year, month, day, hour, minute, second, tz);
3061                                 free(tmp);
3062                                 return err;
3063                         case 'u':
3064                                 pfmt++;
3065                                 scan_type = PGTYPES_TYPE_UINT;
3066                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3067                                 if (scan_val.uint_val < 1 || scan_val.uint_val > 7)
3068                                         err = 1;
3069                                 break;
3070                         case 'U':
3071                                 pfmt++;
3072                                 scan_type = PGTYPES_TYPE_UINT;
3073                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3074                                 if (scan_val.uint_val < 0 || scan_val.uint_val > 53)
3075                                         err = 1;
3076                                 break;
3077                         case 'V':
3078                                 pfmt++;
3079                                 scan_type = PGTYPES_TYPE_UINT;
3080                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3081                                 if (scan_val.uint_val < 1 || scan_val.uint_val > 53)
3082                                         err = 1;
3083                                 break;
3084                         case 'w':
3085                                 pfmt++;
3086                                 scan_type = PGTYPES_TYPE_UINT;
3087                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3088                                 if (scan_val.uint_val < 0 || scan_val.uint_val > 6)
3089                                         err = 1;
3090                                 break;
3091                         case 'W':
3092                                 pfmt++;
3093                                 scan_type = PGTYPES_TYPE_UINT;
3094                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3095                                 if (scan_val.uint_val < 0 || scan_val.uint_val > 53)
3096                                         err = 1;
3097                                 break;
3098                         case 'x':
3099                         case 'X':
3100                                 /* XXX */
3101                                 break;
3102                         case 'Y':
3103                                 pfmt++;
3104                                 scan_type = PGTYPES_TYPE_UINT;
3105                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3106                                 *year = scan_val.uint_val;
3107                                 break;
3108                         case 'z':
3109                                 pfmt++;
3110                                 scan_type = PGTYPES_TYPE_STRING_MALLOCED;
3111                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3112                                 if (!err)
3113                                 {
3114                                         err = DecodeTimezone(scan_val.str_val, tz);
3115                                         free(scan_val.str_val);
3116                                 }
3117                                 break;
3118                         case 'Z':
3119                                 pfmt++;
3120                                 scan_type = PGTYPES_TYPE_STRING_MALLOCED;
3121                                 err = pgtypes_defmt_scan(&scan_val, scan_type, &pstr, pfmt);
3122
3123                                 /*
3124                                  * XXX use DecodeSpecial instead ? - it's declared static
3125                                  * but the arrays as well. :-(
3126                                  */
3127                                 for (j = 0; !err && j < szdatetktbl; j++)
3128                                 {
3129                                         if (strcasecmp(datetktbl[j].token, scan_val.str_val) == 0)
3130                                         {
3131                                                 /*
3132                                                  * tz calculates the offset for the seconds, the
3133                                                  * timezone value of the datetktbl table is in
3134                                                  * quarter hours
3135                                                  */
3136                                                 *tz = -15 * 60 * datetktbl[j].value;
3137                                                 break;
3138                                         }
3139                                 }
3140                                 free(scan_val.str_val);
3141                                 break;
3142                         case '+':
3143                                 /* XXX */
3144                                 break;
3145                         case '%':
3146                                 pfmt++;
3147                                 if (*pstr == '%')
3148                                         pstr++;
3149                                 else
3150                                         err = 1;
3151                                 break;
3152                         default:
3153                                 err = 1;
3154                 }
3155         }
3156         if (!err)
3157         {
3158                 if (*second < 0)
3159                         *second = 0;
3160                 if (*minute < 0)
3161                         *minute = 0;
3162                 if (*hour < 0)
3163                         *hour = 0;
3164                 if (*day < 0)
3165                 {
3166                         err = 1;
3167                         *day = 1;
3168                 }
3169                 if (*month < 0)
3170                 {
3171                         err = 1;
3172                         *month = 1;
3173                 }
3174                 if (*year < 0)
3175                 {
3176                         err = 1;
3177                         *year = 1970;
3178                 }
3179
3180                 if (*second > 59)
3181                 {
3182                         err = 1;
3183                         *second = 0;
3184                 }
3185                 if (*minute > 59)
3186                 {
3187                         err = 1;
3188                         *minute = 0;
3189                 }
3190                 if (*hour > 23)
3191                 {
3192                         err = 1;
3193                         *hour = 0;
3194                 }
3195                 if (*month > 12)
3196                 {
3197                         err = 1;
3198                         *month = 1;
3199                 }
3200                 if (*day > day_tab[isleap(*year)][*month - 1])
3201                 {
3202                         *day = day_tab[isleap(*year)][*month - 1];
3203                         err = 1;
3204                 }
3205
3206                 tm.tm_sec = *second;
3207                 tm.tm_min = *minute;
3208                 tm.tm_hour = *hour;
3209                 tm.tm_mday = *day;
3210                 tm.tm_mon = *month;
3211                 tm.tm_year = *year;
3212
3213                 tm2timestamp(&tm, 0, tz, d);
3214         }
3215         return err;
3216 }
3217
3218 /* XXX: 1900 is compiled in as the base for years */