prtime.cc revision ddb351dbec246cf1fab5ec20d2d5520909041de1
1/* Portions are Copyright (C) 2011 Google Inc */
2/* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
4 *
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
9 *
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
14 *
15 * The Original Code is the Netscape Portable Runtime (NSPR).
16 *
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998-2000
20 * the Initial Developer. All Rights Reserved.
21 *
22 * Contributor(s):
23 *
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
35 *
36 * ***** END LICENSE BLOCK ***** */
37
38/*
39 * prtime.cc --
40 * NOTE: The original nspr file name is prtime.c
41 *
42 *     NSPR date and time functions
43 *
44 * CVS revision 3.37
45 */
46
47/*
48 * The following functions were copied from the NSPR prtime.c file.
49 * PR_ParseTimeString
50 *   We inlined the new PR_ParseTimeStringToExplodedTime function to avoid
51 *   copying PR_ExplodeTime and PR_LocalTimeParameters.  (The PR_ExplodeTime
52 *   and PR_ImplodeTime calls cancel each other out.)
53 * PR_NormalizeTime
54 * PR_GMTParameters
55 * PR_ImplodeTime
56 *   This was modified to use the Win32 SYSTEMTIME/FILETIME structures
57 *   and the timezone offsets are applied to the FILETIME structure.
58 * All types and macros are defined in the base/third_party/prtime.h file.
59 * These have been copied from the following nspr files. We have only copied
60 * over the types we need.
61 * 1. prtime.h
62 * 2. prtypes.h
63 * 3. prlong.h
64 */
65
66#include "base/logging.h"
67#include "base/third_party/nspr/prtime.h"
68#include "build/build_config.h"
69
70#if defined(OS_WIN)
71#include <windows.h>
72#elif defined(OS_MACOSX)
73#include <CoreFoundation/CoreFoundation.h>
74#endif
75#include <errno.h>  /* for EINVAL */
76#include <time.h>
77
78/* Implements the Unix localtime_r() function for windows */
79#if defined(OS_WIN)
80static void localtime_r(const time_t* secs, struct tm* time) {
81  (void) localtime_s(time, secs);
82}
83#endif
84
85/*
86 *------------------------------------------------------------------------
87 *
88 * PR_ImplodeTime --
89 *
90 *     Cf. time_t mktime(struct tm *tp)
91 *     Note that 1 year has < 2^25 seconds.  So an PRInt32 is large enough.
92 *
93 *------------------------------------------------------------------------
94 */
95PRTime
96PR_ImplodeTime(const PRExplodedTime *exploded)
97{
98    // This is important, we want to make sure multiplications are
99    // done with the correct precision.
100    static const PRTime kSecondsToMicroseconds = static_cast<PRTime>(1000000);
101#if defined(OS_WIN)
102   // Create the system struct representing our exploded time.
103    SYSTEMTIME st = {0};
104    FILETIME ft = {0};
105    ULARGE_INTEGER uli = {0};
106
107    st.wYear = exploded->tm_year;
108    st.wMonth = exploded->tm_month + 1;
109    st.wDayOfWeek = exploded->tm_wday;
110    st.wDay = exploded->tm_mday;
111    st.wHour = exploded->tm_hour;
112    st.wMinute = exploded->tm_min;
113    st.wSecond = exploded->tm_sec;
114    st.wMilliseconds = exploded->tm_usec/1000;
115     // Convert to FILETIME.
116    if (!SystemTimeToFileTime(&st, &ft)) {
117      NOTREACHED() << "Unable to convert time";
118      return 0;
119    }
120    // Apply offsets.
121    uli.LowPart = ft.dwLowDateTime;
122    uli.HighPart = ft.dwHighDateTime;
123    // Convert from Windows epoch to NSPR epoch, and 100-nanoseconds units
124    // to microsecond units.
125    PRTime result =
126        static_cast<PRTime>((uli.QuadPart / 10) - 11644473600000000i64);
127    // Adjust for time zone and dst.  Convert from seconds to microseconds.
128    result -= (exploded->tm_params.tp_gmt_offset +
129               exploded->tm_params.tp_dst_offset) * kSecondsToMicroseconds;
130    return result;
131#elif defined(OS_MACOSX)
132    // Create the system struct representing our exploded time.
133    CFGregorianDate gregorian_date;
134    gregorian_date.year = exploded->tm_year;
135    gregorian_date.month = exploded->tm_month + 1;
136    gregorian_date.day = exploded->tm_mday;
137    gregorian_date.hour = exploded->tm_hour;
138    gregorian_date.minute = exploded->tm_min;
139    gregorian_date.second = exploded->tm_sec;
140
141    // Compute |absolute_time| in seconds, correct for gmt and dst
142    // (note the combined offset will be negative when we need to add it), then
143    // convert to microseconds which is what PRTime expects.
144    CFAbsoluteTime absolute_time =
145        CFGregorianDateGetAbsoluteTime(gregorian_date, NULL);
146    PRTime result = static_cast<PRTime>(absolute_time);
147    result -= exploded->tm_params.tp_gmt_offset +
148              exploded->tm_params.tp_dst_offset;
149    result += kCFAbsoluteTimeIntervalSince1970;  // PRTime epoch is 1970
150    result *= kSecondsToMicroseconds;
151    result += exploded->tm_usec;
152    return result;
153#elif defined(OS_POSIX)
154    struct tm exp_tm = {0};
155    exp_tm.tm_sec  = exploded->tm_sec;
156    exp_tm.tm_min  = exploded->tm_min;
157    exp_tm.tm_hour = exploded->tm_hour;
158    exp_tm.tm_mday = exploded->tm_mday;
159    exp_tm.tm_mon  = exploded->tm_month;
160    exp_tm.tm_year = exploded->tm_year - 1900;
161
162    time_t absolute_time = timegm(&exp_tm);
163
164    // If timegm returned -1.  Since we don't pass it a time zone, the only
165    // valid case of returning -1 is 1 second before Epoch (Dec 31, 1969).
166    if (absolute_time == -1 &&
167        !(exploded->tm_year == 1969 && exploded->tm_month == 11 &&
168        exploded->tm_mday == 31 && exploded->tm_hour == 23 &&
169        exploded->tm_min == 59 && exploded->tm_sec == 59)) {
170      // If we get here, time_t must be 32 bits.
171      // Date was possibly too far in the future and would overflow.  Return
172      // the most future date possible (year 2038).
173      if (exploded->tm_year >= 1970)
174        return INT_MAX * kSecondsToMicroseconds;
175      // Date was possibly too far in the past and would underflow.  Return
176      // the most past date possible (year 1901).
177      return INT_MIN * kSecondsToMicroseconds;
178    }
179
180    PRTime result = static_cast<PRTime>(absolute_time);
181    result -= exploded->tm_params.tp_gmt_offset +
182              exploded->tm_params.tp_dst_offset;
183    result *= kSecondsToMicroseconds;
184    result += exploded->tm_usec;
185    return result;
186#else
187#error No PR_ImplodeTime implemented on your platform.
188#endif
189}
190
191/*
192 * The COUNT_LEAPS macro counts the number of leap years passed by
193 * till the start of the given year Y.  At the start of the year 4
194 * A.D. the number of leap years passed by is 0, while at the start of
195 * the year 5 A.D. this count is 1. The number of years divisible by
196 * 100 but not divisible by 400 (the non-leap years) is deducted from
197 * the count to get the correct number of leap years.
198 *
199 * The COUNT_DAYS macro counts the number of days since 01/01/01 till the
200 * start of the given year Y. The number of days at the start of the year
201 * 1 is 0 while the number of days at the start of the year 2 is 365
202 * (which is ((2)-1) * 365) and so on. The reference point is 01/01/01
203 * midnight 00:00:00.
204 */
205
206#define COUNT_LEAPS(Y)   ( ((Y)-1)/4 - ((Y)-1)/100 + ((Y)-1)/400 )
207#define COUNT_DAYS(Y)  ( ((Y)-1)*365 + COUNT_LEAPS(Y) )
208#define DAYS_BETWEEN_YEARS(A, B)  (COUNT_DAYS(B) - COUNT_DAYS(A))
209
210/*
211 * Static variables used by functions in this file
212 */
213
214/*
215 * The following array contains the day of year for the last day of
216 * each month, where index 1 is January, and day 0 is January 1.
217 */
218
219static const int lastDayOfMonth[2][13] = {
220    {-1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364},
221    {-1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
222};
223
224/*
225 * The number of days in a month
226 */
227
228static const PRInt8 nDays[2][12] = {
229    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
230    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
231};
232
233/*
234 *-------------------------------------------------------------------------
235 *
236 * IsLeapYear --
237 *
238 *     Returns 1 if the year is a leap year, 0 otherwise.
239 *
240 *-------------------------------------------------------------------------
241 */
242
243static int IsLeapYear(PRInt16 year)
244{
245    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
246        return 1;
247    else
248        return 0;
249}
250
251/*
252 * 'secOffset' should be less than 86400 (i.e., a day).
253 * 'time' should point to a normalized PRExplodedTime.
254 */
255
256static void
257ApplySecOffset(PRExplodedTime *time, PRInt32 secOffset)
258{
259    time->tm_sec += secOffset;
260
261    /* Note that in this implementation we do not count leap seconds */
262    if (time->tm_sec < 0 || time->tm_sec >= 60) {
263        time->tm_min += time->tm_sec / 60;
264        time->tm_sec %= 60;
265        if (time->tm_sec < 0) {
266            time->tm_sec += 60;
267            time->tm_min--;
268        }
269    }
270
271    if (time->tm_min < 0 || time->tm_min >= 60) {
272        time->tm_hour += time->tm_min / 60;
273        time->tm_min %= 60;
274        if (time->tm_min < 0) {
275            time->tm_min += 60;
276            time->tm_hour--;
277        }
278    }
279
280    if (time->tm_hour < 0) {
281        /* Decrement mday, yday, and wday */
282        time->tm_hour += 24;
283        time->tm_mday--;
284        time->tm_yday--;
285        if (time->tm_mday < 1) {
286            time->tm_month--;
287            if (time->tm_month < 0) {
288                time->tm_month = 11;
289                time->tm_year--;
290                if (IsLeapYear(time->tm_year))
291                    time->tm_yday = 365;
292                else
293                    time->tm_yday = 364;
294            }
295            time->tm_mday = nDays[IsLeapYear(time->tm_year)][time->tm_month];
296        }
297        time->tm_wday--;
298        if (time->tm_wday < 0)
299            time->tm_wday = 6;
300    } else if (time->tm_hour > 23) {
301        /* Increment mday, yday, and wday */
302        time->tm_hour -= 24;
303        time->tm_mday++;
304        time->tm_yday++;
305        if (time->tm_mday >
306                nDays[IsLeapYear(time->tm_year)][time->tm_month]) {
307            time->tm_mday = 1;
308            time->tm_month++;
309            if (time->tm_month > 11) {
310                time->tm_month = 0;
311                time->tm_year++;
312                time->tm_yday = 0;
313            }
314        }
315        time->tm_wday++;
316        if (time->tm_wday > 6)
317            time->tm_wday = 0;
318    }
319}
320
321void
322PR_NormalizeTime(PRExplodedTime *time, PRTimeParamFn params)
323{
324    int daysInMonth;
325    PRInt32 numDays;
326
327    /* Get back to GMT */
328    time->tm_sec -= time->tm_params.tp_gmt_offset
329            + time->tm_params.tp_dst_offset;
330    time->tm_params.tp_gmt_offset = 0;
331    time->tm_params.tp_dst_offset = 0;
332
333    /* Now normalize GMT */
334
335    if (time->tm_usec < 0 || time->tm_usec >= 1000000) {
336        time->tm_sec +=  time->tm_usec / 1000000;
337        time->tm_usec %= 1000000;
338        if (time->tm_usec < 0) {
339            time->tm_usec += 1000000;
340            time->tm_sec--;
341        }
342    }
343
344    /* Note that we do not count leap seconds in this implementation */
345    if (time->tm_sec < 0 || time->tm_sec >= 60) {
346        time->tm_min += time->tm_sec / 60;
347        time->tm_sec %= 60;
348        if (time->tm_sec < 0) {
349            time->tm_sec += 60;
350            time->tm_min--;
351        }
352    }
353
354    if (time->tm_min < 0 || time->tm_min >= 60) {
355        time->tm_hour += time->tm_min / 60;
356        time->tm_min %= 60;
357        if (time->tm_min < 0) {
358            time->tm_min += 60;
359            time->tm_hour--;
360        }
361    }
362
363    if (time->tm_hour < 0 || time->tm_hour >= 24) {
364        time->tm_mday += time->tm_hour / 24;
365        time->tm_hour %= 24;
366        if (time->tm_hour < 0) {
367            time->tm_hour += 24;
368            time->tm_mday--;
369        }
370    }
371
372    /* Normalize month and year before mday */
373    if (time->tm_month < 0 || time->tm_month >= 12) {
374        time->tm_year += time->tm_month / 12;
375        time->tm_month %= 12;
376        if (time->tm_month < 0) {
377            time->tm_month += 12;
378            time->tm_year--;
379        }
380    }
381
382    /* Now that month and year are in proper range, normalize mday */
383
384    if (time->tm_mday < 1) {
385        /* mday too small */
386        do {
387            /* the previous month */
388            time->tm_month--;
389            if (time->tm_month < 0) {
390                time->tm_month = 11;
391                time->tm_year--;
392            }
393            time->tm_mday += nDays[IsLeapYear(time->tm_year)][time->tm_month];
394        } while (time->tm_mday < 1);
395    } else {
396        daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
397        while (time->tm_mday > daysInMonth) {
398            /* mday too large */
399            time->tm_mday -= daysInMonth;
400            time->tm_month++;
401            if (time->tm_month > 11) {
402                time->tm_month = 0;
403                time->tm_year++;
404            }
405            daysInMonth = nDays[IsLeapYear(time->tm_year)][time->tm_month];
406        }
407    }
408
409    /* Recompute yday and wday */
410    time->tm_yday = time->tm_mday +
411            lastDayOfMonth[IsLeapYear(time->tm_year)][time->tm_month];
412
413    numDays = DAYS_BETWEEN_YEARS(1970, time->tm_year) + time->tm_yday;
414    time->tm_wday = (numDays + 4) % 7;
415    if (time->tm_wday < 0) {
416        time->tm_wday += 7;
417    }
418
419    /* Recompute time parameters */
420
421    time->tm_params = params(time);
422
423    ApplySecOffset(time, time->tm_params.tp_gmt_offset
424            + time->tm_params.tp_dst_offset);
425}
426
427/*
428 *------------------------------------------------------------------------
429 *
430 * PR_GMTParameters --
431 *
432 *     Returns the PRTimeParameters for Greenwich Mean Time.
433 *     Trivially, both the tp_gmt_offset and tp_dst_offset fields are 0.
434 *
435 *------------------------------------------------------------------------
436 */
437
438PRTimeParameters
439PR_GMTParameters(const PRExplodedTime *gmt)
440{
441#if defined(XP_MAC)
442#pragma unused (gmt)
443#endif
444
445    PRTimeParameters retVal = { 0, 0 };
446    return retVal;
447}
448
449/*
450 * The following code implements PR_ParseTimeString().  It is based on
451 * ns/lib/xp/xp_time.c, revision 1.25, by Jamie Zawinski <jwz@netscape.com>.
452 */
453
454/*
455 * We only recognize the abbreviations of a small subset of time zones
456 * in North America, Europe, and Japan.
457 *
458 * PST/PDT: Pacific Standard/Daylight Time
459 * MST/MDT: Mountain Standard/Daylight Time
460 * CST/CDT: Central Standard/Daylight Time
461 * EST/EDT: Eastern Standard/Daylight Time
462 * AST: Atlantic Standard Time
463 * NST: Newfoundland Standard Time
464 * GMT: Greenwich Mean Time
465 * BST: British Summer Time
466 * MET: Middle Europe Time
467 * EET: Eastern Europe Time
468 * JST: Japan Standard Time
469 */
470
471typedef enum
472{
473  TT_UNKNOWN,
474
475  TT_SUN, TT_MON, TT_TUE, TT_WED, TT_THU, TT_FRI, TT_SAT,
476
477  TT_JAN, TT_FEB, TT_MAR, TT_APR, TT_MAY, TT_JUN,
478  TT_JUL, TT_AUG, TT_SEP, TT_OCT, TT_NOV, TT_DEC,
479
480  TT_PST, TT_PDT, TT_MST, TT_MDT, TT_CST, TT_CDT, TT_EST, TT_EDT,
481  TT_AST, TT_NST, TT_GMT, TT_BST, TT_MET, TT_EET, TT_JST
482} TIME_TOKEN;
483
484/*
485 * This parses a time/date string into a PRTime
486 * (microseconds after "1-Jan-1970 00:00:00 GMT").
487 * It returns PR_SUCCESS on success, and PR_FAILURE
488 * if the time/date string can't be parsed.
489 *
490 * Many formats are handled, including:
491 *
492 *   14 Apr 89 03:20:12
493 *   14 Apr 89 03:20 GMT
494 *   Fri, 17 Mar 89 4:01:33
495 *   Fri, 17 Mar 89 4:01 GMT
496 *   Mon Jan 16 16:12 PDT 1989
497 *   Mon Jan 16 16:12 +0130 1989
498 *   6 May 1992 16:41-JST (Wednesday)
499 *   22-AUG-1993 10:59:12.82
500 *   22-AUG-1993 10:59pm
501 *   22-AUG-1993 12:59am
502 *   22-AUG-1993 12:59 PM
503 *   Friday, August 04, 1995 3:54 PM
504 *   06/21/95 04:24:34 PM
505 *   20/06/95 21:07
506 *   95-06-08 19:32:48 EDT
507 *
508 * If the input string doesn't contain a description of the timezone,
509 * we consult the `default_to_gmt' to decide whether the string should
510 * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE).
511 * The correct value for this argument depends on what standard specified
512 * the time string which you are parsing.
513 */
514
515PRStatus
516PR_ParseTimeString(
517        const char *string,
518        PRBool default_to_gmt,
519        PRTime *result_imploded)
520{
521  PRExplodedTime tm;
522  PRExplodedTime *result = &tm;
523  TIME_TOKEN dotw = TT_UNKNOWN;
524  TIME_TOKEN month = TT_UNKNOWN;
525  TIME_TOKEN zone = TT_UNKNOWN;
526  int zone_offset = -1;
527  int dst_offset = 0;
528  int date = -1;
529  PRInt32 year = -1;
530  int hour = -1;
531  int min = -1;
532  int sec = -1;
533
534  const char *rest = string;
535
536  int iterations = 0;
537
538  PR_ASSERT(string && result);
539  if (!string || !result) return PR_FAILURE;
540
541  while (*rest)
542        {
543
544          if (iterations++ > 1000)
545                {
546                  return PR_FAILURE;
547                }
548
549          switch (*rest)
550                {
551                case 'a': case 'A':
552                  if (month == TT_UNKNOWN &&
553                          (rest[1] == 'p' || rest[1] == 'P') &&
554                          (rest[2] == 'r' || rest[2] == 'R'))
555                        month = TT_APR;
556                  else if (zone == TT_UNKNOWN &&
557                                   (rest[1] == 's' || rest[1] == 'S') &&
558                                   (rest[2] == 't' || rest[2] == 'T'))
559                        zone = TT_AST;
560                  else if (month == TT_UNKNOWN &&
561                                   (rest[1] == 'u' || rest[1] == 'U') &&
562                                   (rest[2] == 'g' || rest[2] == 'G'))
563                        month = TT_AUG;
564                  break;
565                case 'b': case 'B':
566                  if (zone == TT_UNKNOWN &&
567                          (rest[1] == 's' || rest[1] == 'S') &&
568                          (rest[2] == 't' || rest[2] == 'T'))
569                        zone = TT_BST;
570                  break;
571                case 'c': case 'C':
572                  if (zone == TT_UNKNOWN &&
573                          (rest[1] == 'd' || rest[1] == 'D') &&
574                          (rest[2] == 't' || rest[2] == 'T'))
575                        zone = TT_CDT;
576                  else if (zone == TT_UNKNOWN &&
577                                   (rest[1] == 's' || rest[1] == 'S') &&
578                                   (rest[2] == 't' || rest[2] == 'T'))
579                        zone = TT_CST;
580                  break;
581                case 'd': case 'D':
582                  if (month == TT_UNKNOWN &&
583                          (rest[1] == 'e' || rest[1] == 'E') &&
584                          (rest[2] == 'c' || rest[2] == 'C'))
585                        month = TT_DEC;
586                  break;
587                case 'e': case 'E':
588                  if (zone == TT_UNKNOWN &&
589                          (rest[1] == 'd' || rest[1] == 'D') &&
590                          (rest[2] == 't' || rest[2] == 'T'))
591                        zone = TT_EDT;
592                  else if (zone == TT_UNKNOWN &&
593                                   (rest[1] == 'e' || rest[1] == 'E') &&
594                                   (rest[2] == 't' || rest[2] == 'T'))
595                        zone = TT_EET;
596                  else if (zone == TT_UNKNOWN &&
597                                   (rest[1] == 's' || rest[1] == 'S') &&
598                                   (rest[2] == 't' || rest[2] == 'T'))
599                        zone = TT_EST;
600                  break;
601                case 'f': case 'F':
602                  if (month == TT_UNKNOWN &&
603                          (rest[1] == 'e' || rest[1] == 'E') &&
604                          (rest[2] == 'b' || rest[2] == 'B'))
605                        month = TT_FEB;
606                  else if (dotw == TT_UNKNOWN &&
607                                   (rest[1] == 'r' || rest[1] == 'R') &&
608                                   (rest[2] == 'i' || rest[2] == 'I'))
609                        dotw = TT_FRI;
610                  break;
611                case 'g': case 'G':
612                  if (zone == TT_UNKNOWN &&
613                          (rest[1] == 'm' || rest[1] == 'M') &&
614                          (rest[2] == 't' || rest[2] == 'T'))
615                        zone = TT_GMT;
616                  break;
617                case 'j': case 'J':
618                  if (month == TT_UNKNOWN &&
619                          (rest[1] == 'a' || rest[1] == 'A') &&
620                          (rest[2] == 'n' || rest[2] == 'N'))
621                        month = TT_JAN;
622                  else if (zone == TT_UNKNOWN &&
623                                   (rest[1] == 's' || rest[1] == 'S') &&
624                                   (rest[2] == 't' || rest[2] == 'T'))
625                        zone = TT_JST;
626                  else if (month == TT_UNKNOWN &&
627                                   (rest[1] == 'u' || rest[1] == 'U') &&
628                                   (rest[2] == 'l' || rest[2] == 'L'))
629                        month = TT_JUL;
630                  else if (month == TT_UNKNOWN &&
631                                   (rest[1] == 'u' || rest[1] == 'U') &&
632                                   (rest[2] == 'n' || rest[2] == 'N'))
633                        month = TT_JUN;
634                  break;
635                case 'm': case 'M':
636                  if (month == TT_UNKNOWN &&
637                          (rest[1] == 'a' || rest[1] == 'A') &&
638                          (rest[2] == 'r' || rest[2] == 'R'))
639                        month = TT_MAR;
640                  else if (month == TT_UNKNOWN &&
641                                   (rest[1] == 'a' || rest[1] == 'A') &&
642                                   (rest[2] == 'y' || rest[2] == 'Y'))
643                        month = TT_MAY;
644                  else if (zone == TT_UNKNOWN &&
645                                   (rest[1] == 'd' || rest[1] == 'D') &&
646                                   (rest[2] == 't' || rest[2] == 'T'))
647                        zone = TT_MDT;
648                  else if (zone == TT_UNKNOWN &&
649                                   (rest[1] == 'e' || rest[1] == 'E') &&
650                                   (rest[2] == 't' || rest[2] == 'T'))
651                        zone = TT_MET;
652                  else if (dotw == TT_UNKNOWN &&
653                                   (rest[1] == 'o' || rest[1] == 'O') &&
654                                   (rest[2] == 'n' || rest[2] == 'N'))
655                        dotw = TT_MON;
656                  else if (zone == TT_UNKNOWN &&
657                                   (rest[1] == 's' || rest[1] == 'S') &&
658                                   (rest[2] == 't' || rest[2] == 'T'))
659                        zone = TT_MST;
660                  break;
661                case 'n': case 'N':
662                  if (month == TT_UNKNOWN &&
663                          (rest[1] == 'o' || rest[1] == 'O') &&
664                          (rest[2] == 'v' || rest[2] == 'V'))
665                        month = TT_NOV;
666                  else if (zone == TT_UNKNOWN &&
667                                   (rest[1] == 's' || rest[1] == 'S') &&
668                                   (rest[2] == 't' || rest[2] == 'T'))
669                        zone = TT_NST;
670                  break;
671                case 'o': case 'O':
672                  if (month == TT_UNKNOWN &&
673                          (rest[1] == 'c' || rest[1] == 'C') &&
674                          (rest[2] == 't' || rest[2] == 'T'))
675                        month = TT_OCT;
676                  break;
677                case 'p': case 'P':
678                  if (zone == TT_UNKNOWN &&
679                          (rest[1] == 'd' || rest[1] == 'D') &&
680                          (rest[2] == 't' || rest[2] == 'T'))
681                        zone = TT_PDT;
682                  else if (zone == TT_UNKNOWN &&
683                                   (rest[1] == 's' || rest[1] == 'S') &&
684                                   (rest[2] == 't' || rest[2] == 'T'))
685                        zone = TT_PST;
686                  break;
687                case 's': case 'S':
688                  if (dotw == TT_UNKNOWN &&
689                          (rest[1] == 'a' || rest[1] == 'A') &&
690                          (rest[2] == 't' || rest[2] == 'T'))
691                        dotw = TT_SAT;
692                  else if (month == TT_UNKNOWN &&
693                                   (rest[1] == 'e' || rest[1] == 'E') &&
694                                   (rest[2] == 'p' || rest[2] == 'P'))
695                        month = TT_SEP;
696                  else if (dotw == TT_UNKNOWN &&
697                                   (rest[1] == 'u' || rest[1] == 'U') &&
698                                   (rest[2] == 'n' || rest[2] == 'N'))
699                        dotw = TT_SUN;
700                  break;
701                case 't': case 'T':
702                  if (dotw == TT_UNKNOWN &&
703                          (rest[1] == 'h' || rest[1] == 'H') &&
704                          (rest[2] == 'u' || rest[2] == 'U'))
705                        dotw = TT_THU;
706                  else if (dotw == TT_UNKNOWN &&
707                                   (rest[1] == 'u' || rest[1] == 'U') &&
708                                   (rest[2] == 'e' || rest[2] == 'E'))
709                        dotw = TT_TUE;
710                  break;
711                case 'u': case 'U':
712                  if (zone == TT_UNKNOWN &&
713                          (rest[1] == 't' || rest[1] == 'T') &&
714                          !(rest[2] >= 'A' && rest[2] <= 'Z') &&
715                          !(rest[2] >= 'a' && rest[2] <= 'z'))
716                        /* UT is the same as GMT but UTx is not. */
717                        zone = TT_GMT;
718                  break;
719                case 'w': case 'W':
720                  if (dotw == TT_UNKNOWN &&
721                          (rest[1] == 'e' || rest[1] == 'E') &&
722                          (rest[2] == 'd' || rest[2] == 'D'))
723                        dotw = TT_WED;
724                  break;
725
726                case '+': case '-':
727                  {
728                        const char *end;
729                        int sign;
730                        if (zone_offset != -1)
731                          {
732                                /* already got one... */
733                                rest++;
734                                break;
735                          }
736                        if (zone != TT_UNKNOWN && zone != TT_GMT)
737                          {
738                                /* GMT+0300 is legal, but PST+0300 is not. */
739                                rest++;
740                                break;
741                          }
742
743                        sign = ((*rest == '+') ? 1 : -1);
744                        rest++; /* move over sign */
745                        end = rest;
746                        while (*end >= '0' && *end <= '9')
747                          end++;
748                        if (rest == end) /* no digits here */
749                          break;
750
751                        if ((end - rest) == 4)
752                          /* offset in HHMM */
753                          zone_offset = (((((rest[0]-'0')*10) + (rest[1]-'0')) * 60) +
754                                                         (((rest[2]-'0')*10) + (rest[3]-'0')));
755                        else if ((end - rest) == 2)
756                          /* offset in hours */
757                          zone_offset = (((rest[0]-'0')*10) + (rest[1]-'0')) * 60;
758                        else if ((end - rest) == 1)
759                          /* offset in hours */
760                          zone_offset = (rest[0]-'0') * 60;
761                        else
762                          /* 3 or >4 */
763                          break;
764
765                        zone_offset *= sign;
766                        zone = TT_GMT;
767                        break;
768                  }
769
770                case '0': case '1': case '2': case '3': case '4':
771                case '5': case '6': case '7': case '8': case '9':
772                  {
773                        int tmp_hour = -1;
774                        int tmp_min = -1;
775                        int tmp_sec = -1;
776                        const char *end = rest + 1;
777                        while (*end >= '0' && *end <= '9')
778                          end++;
779
780                        /* end is now the first character after a range of digits. */
781
782                        if (*end == ':')
783                          {
784                                if (hour >= 0 && min >= 0) /* already got it */
785                                  break;
786
787                                /* We have seen "[0-9]+:", so this is probably HH:MM[:SS] */
788                                if ((end - rest) > 2)
789                                  /* it is [0-9][0-9][0-9]+: */
790                                  break;
791                                else if ((end - rest) == 2)
792                                  tmp_hour = ((rest[0]-'0')*10 +
793                                                          (rest[1]-'0'));
794                                else
795                                  tmp_hour = (rest[0]-'0');
796
797                                /* move over the colon, and parse minutes */
798
799                                rest = ++end;
800                                while (*end >= '0' && *end <= '9')
801                                  end++;
802
803                                if (end == rest)
804                                  /* no digits after first colon? */
805                                  break;
806                                else if ((end - rest) > 2)
807                                  /* it is [0-9][0-9][0-9]+: */
808                                  break;
809                                else if ((end - rest) == 2)
810                                  tmp_min = ((rest[0]-'0')*10 +
811                                                         (rest[1]-'0'));
812                                else
813                                  tmp_min = (rest[0]-'0');
814
815                                /* now go for seconds */
816                                rest = end;
817                                if (*rest == ':')
818                                  rest++;
819                                end = rest;
820                                while (*end >= '0' && *end <= '9')
821                                  end++;
822
823                                if (end == rest)
824                                  /* no digits after second colon - that's ok. */
825                                  ;
826                                else if ((end - rest) > 2)
827                                  /* it is [0-9][0-9][0-9]+: */
828                                  break;
829                                else if ((end - rest) == 2)
830                                  tmp_sec = ((rest[0]-'0')*10 +
831                                                         (rest[1]-'0'));
832                                else
833                                  tmp_sec = (rest[0]-'0');
834
835                                /* If we made it here, we've parsed hour and min,
836                                   and possibly sec, so it worked as a unit. */
837
838                                /* skip over whitespace and see if there's an AM or PM
839                                   directly following the time.
840                                 */
841                                if (tmp_hour <= 12)
842                                  {
843                                        const char *s = end;
844                                        while (*s && (*s == ' ' || *s == '\t'))
845                                          s++;
846                                        if ((s[0] == 'p' || s[0] == 'P') &&
847                                                (s[1] == 'm' || s[1] == 'M'))
848                                          /* 10:05pm == 22:05, and 12:05pm == 12:05 */
849                                          tmp_hour = (tmp_hour == 12 ? 12 : tmp_hour + 12);
850                                        else if (tmp_hour == 12 &&
851                                                         (s[0] == 'a' || s[0] == 'A') &&
852                                                         (s[1] == 'm' || s[1] == 'M'))
853                                          /* 12:05am == 00:05 */
854                                          tmp_hour = 0;
855                                  }
856
857                                hour = tmp_hour;
858                                min = tmp_min;
859                                sec = tmp_sec;
860                                rest = end;
861                                break;
862                          }
863                        else if ((*end == '/' || *end == '-') &&
864                                         end[1] >= '0' && end[1] <= '9')
865                          {
866                                /* Perhaps this is 6/16/95, 16/6/95, 6-16-95, or 16-6-95
867                                   or even 95-06-05...
868                                   #### But it doesn't handle 1995-06-22.
869                                 */
870                                int n1, n2, n3;
871                                const char *s;
872
873                                if (month != TT_UNKNOWN)
874                                  /* if we saw a month name, this can't be. */
875                                  break;
876
877                                s = rest;
878
879                                n1 = (*s++ - '0');                                /* first 1 or 2 digits */
880                                if (*s >= '0' && *s <= '9')
881                                  n1 = n1*10 + (*s++ - '0');
882
883                                if (*s != '/' && *s != '-')                /* slash */
884                                  break;
885                                s++;
886
887                                if (*s < '0' || *s > '9')                /* second 1 or 2 digits */
888                                  break;
889                                n2 = (*s++ - '0');
890                                if (*s >= '0' && *s <= '9')
891                                  n2 = n2*10 + (*s++ - '0');
892
893                                if (*s != '/' && *s != '-')                /* slash */
894                                  break;
895                                s++;
896
897                                if (*s < '0' || *s > '9')                /* third 1, 2, 4, or 5 digits */
898                                  break;
899                                n3 = (*s++ - '0');
900                                if (*s >= '0' && *s <= '9')
901                                  n3 = n3*10 + (*s++ - '0');
902
903                                if (*s >= '0' && *s <= '9')            /* optional digits 3, 4, and 5 */
904                                  {
905                                        n3 = n3*10 + (*s++ - '0');
906                                        if (*s < '0' || *s > '9')
907                                          break;
908                                        n3 = n3*10 + (*s++ - '0');
909                                        if (*s >= '0' && *s <= '9')
910                                          n3 = n3*10 + (*s++ - '0');
911                                  }
912
913                                if ((*s >= '0' && *s <= '9') ||        /* followed by non-alphanum */
914                                        (*s >= 'A' && *s <= 'Z') ||
915                                        (*s >= 'a' && *s <= 'z'))
916                                  break;
917
918                                /* Ok, we parsed three 1-2 digit numbers, with / or -
919                                   between them.  Now decide what the hell they are
920                                   (DD/MM/YY or MM/DD/YY or YY/MM/DD.)
921                                 */
922
923                                if (n1 > 31 || n1 == 0)  /* must be YY/MM/DD */
924                                  {
925                                        if (n2 > 12) break;
926                                        if (n3 > 31) break;
927                                        year = n1;
928                                        if (year < 70)
929                                            year += 2000;
930                                        else if (year < 100)
931                                            year += 1900;
932                                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
933                                        date = n3;
934                                        rest = s;
935                                        break;
936                                  }
937
938                                if (n1 > 12 && n2 > 12)  /* illegal */
939                                  {
940                                        rest = s;
941                                        break;
942                                  }
943
944                                if (n3 < 70)
945                                    n3 += 2000;
946                                else if (n3 < 100)
947                                    n3 += 1900;
948
949                                if (n1 > 12)  /* must be DD/MM/YY */
950                                  {
951                                        date = n1;
952                                        month = (TIME_TOKEN)(n2 + ((int)TT_JAN) - 1);
953                                        year = n3;
954                                  }
955                                else                  /* assume MM/DD/YY */
956                                  {
957                                        /* #### In the ambiguous case, should we consult the
958                                           locale to find out the local default? */
959                                        month = (TIME_TOKEN)(n1 + ((int)TT_JAN) - 1);
960                                        date = n2;
961                                        year = n3;
962                                  }
963                                rest = s;
964                          }
965                        else if ((*end >= 'A' && *end <= 'Z') ||
966                                         (*end >= 'a' && *end <= 'z'))
967                          /* Digits followed by non-punctuation - what's that? */
968                          ;
969                        else if ((end - rest) == 5)                /* five digits is a year */
970                          year = (year < 0
971                                          ? ((rest[0]-'0')*10000L +
972                                                 (rest[1]-'0')*1000L +
973                                                 (rest[2]-'0')*100L +
974                                                 (rest[3]-'0')*10L +
975                                                 (rest[4]-'0'))
976                                          : year);
977                        else if ((end - rest) == 4)                /* four digits is a year */
978                          year = (year < 0
979                                          ? ((rest[0]-'0')*1000L +
980                                                 (rest[1]-'0')*100L +
981                                                 (rest[2]-'0')*10L +
982                                                 (rest[3]-'0'))
983                                          : year);
984                        else if ((end - rest) == 2)                /* two digits - date or year */
985                          {
986                                int n = ((rest[0]-'0')*10 +
987                                                 (rest[1]-'0'));
988                                /* If we don't have a date (day of the month) and we see a number
989                                     less than 32, then assume that is the date.
990
991                                         Otherwise, if we have a date and not a year, assume this is the
992                                         year.  If it is less than 70, then assume it refers to the 21st
993                                         century.  If it is two digits (>= 70), assume it refers to this
994                                         century.  Otherwise, assume it refers to an unambiguous year.
995
996                                         The world will surely end soon.
997                                   */
998                                if (date < 0 && n < 32)
999                                  date = n;
1000                                else if (year < 0)
1001                                  {
1002                                        if (n < 70)
1003                                          year = 2000 + n;
1004                                        else if (n < 100)
1005                                          year = 1900 + n;
1006                                        else
1007                                          year = n;
1008                                  }
1009                                /* else what the hell is this. */
1010                          }
1011                        else if ((end - rest) == 1)                /* one digit - date */
1012                          date = (date < 0 ? (rest[0]-'0') : date);
1013                        /* else, three or more than five digits - what's that? */
1014
1015                        break;
1016                  }
1017                }
1018
1019          /* Skip to the end of this token, whether we parsed it or not.
1020                 Tokens are delimited by whitespace, or ,;-/
1021                 But explicitly not :+-.
1022           */
1023          while (*rest &&
1024                         *rest != ' ' && *rest != '\t' &&
1025                         *rest != ',' && *rest != ';' &&
1026                         *rest != '-' && *rest != '+' &&
1027                         *rest != '/' &&
1028                         *rest != '(' && *rest != ')' && *rest != '[' && *rest != ']')
1029                rest++;
1030          /* skip over uninteresting chars. */
1031        SKIP_MORE:
1032          while (*rest &&
1033                         (*rest == ' ' || *rest == '\t' ||
1034                          *rest == ',' || *rest == ';' || *rest == '/' ||
1035                          *rest == '(' || *rest == ')' || *rest == '[' || *rest == ']'))
1036                rest++;
1037
1038          /* "-" is ignored at the beginning of a token if we have not yet
1039                 parsed a year (e.g., the second "-" in "30-AUG-1966"), or if
1040                 the character after the dash is not a digit. */
1041          if (*rest == '-' && ((rest > string && isalpha(rest[-1]) && year < 0)
1042              || rest[1] < '0' || rest[1] > '9'))
1043                {
1044                  rest++;
1045                  goto SKIP_MORE;
1046                }
1047
1048        }
1049
1050  if (zone != TT_UNKNOWN && zone_offset == -1)
1051        {
1052          switch (zone)
1053                {
1054                case TT_PST: zone_offset = -8 * 60; break;
1055                case TT_PDT: zone_offset = -8 * 60; dst_offset = 1 * 60; break;
1056                case TT_MST: zone_offset = -7 * 60; break;
1057                case TT_MDT: zone_offset = -7 * 60; dst_offset = 1 * 60; break;
1058                case TT_CST: zone_offset = -6 * 60; break;
1059                case TT_CDT: zone_offset = -6 * 60; dst_offset = 1 * 60; break;
1060                case TT_EST: zone_offset = -5 * 60; break;
1061                case TT_EDT: zone_offset = -5 * 60; dst_offset = 1 * 60; break;
1062                case TT_AST: zone_offset = -4 * 60; break;
1063                case TT_NST: zone_offset = -3 * 60 - 30; break;
1064                case TT_GMT: zone_offset =  0 * 60; break;
1065                case TT_BST: zone_offset =  0 * 60; dst_offset = 1 * 60; break;
1066                case TT_MET: zone_offset =  1 * 60; break;
1067                case TT_EET: zone_offset =  2 * 60; break;
1068                case TT_JST: zone_offset =  9 * 60; break;
1069                default:
1070                  PR_ASSERT (0);
1071                  break;
1072                }
1073        }
1074
1075  /* If we didn't find a year, month, or day-of-the-month, we can't
1076         possibly parse this, and in fact, mktime() will do something random
1077         (I'm seeing it return "Tue Feb  5 06:28:16 2036", which is no doubt
1078         a numerologically significant date... */
1079  if (month == TT_UNKNOWN || date == -1 || year == -1 || year > PR_INT16_MAX)
1080      return PR_FAILURE;
1081
1082  memset(result, 0, sizeof(*result));
1083  if (sec != -1)
1084        result->tm_sec = sec;
1085  if (min != -1)
1086        result->tm_min = min;
1087  if (hour != -1)
1088        result->tm_hour = hour;
1089  if (date != -1)
1090        result->tm_mday = date;
1091  if (month != TT_UNKNOWN)
1092        result->tm_month = (((int)month) - ((int)TT_JAN));
1093  if (year != -1)
1094        result->tm_year = year;
1095  if (dotw != TT_UNKNOWN)
1096        result->tm_wday = (((int)dotw) - ((int)TT_SUN));
1097  /*
1098   * Mainly to compute wday and yday, but normalized time is also required
1099   * by the check below that works around a Visual C++ 2005 mktime problem.
1100   */
1101  PR_NormalizeTime(result, PR_GMTParameters);
1102  /* The remaining work is to set the gmt and dst offsets in tm_params. */
1103
1104  if (zone == TT_UNKNOWN && default_to_gmt)
1105        {
1106          /* No zone was specified, so pretend the zone was GMT. */
1107          zone = TT_GMT;
1108          zone_offset = 0;
1109        }
1110
1111  if (zone_offset == -1)
1112         {
1113           /* no zone was specified, and we're to assume that everything
1114             is local. */
1115          struct tm localTime;
1116          time_t secs;
1117
1118          PR_ASSERT(result->tm_month > -1 &&
1119                    result->tm_mday > 0 &&
1120                    result->tm_hour > -1 &&
1121                    result->tm_min > -1 &&
1122                    result->tm_sec > -1);
1123
1124            /*
1125             * To obtain time_t from a tm structure representing the local
1126             * time, we call mktime().  However, we need to see if we are
1127             * on 1-Jan-1970 or before.  If we are, we can't call mktime()
1128             * because mktime() will crash on win16. In that case, we
1129             * calculate zone_offset based on the zone offset at
1130             * 00:00:00, 2 Jan 1970 GMT, and subtract zone_offset from the
1131             * date we are parsing to transform the date to GMT.  We also
1132             * do so if mktime() returns (time_t) -1 (time out of range).
1133           */
1134
1135          /* month, day, hours, mins and secs are always non-negative
1136             so we dont need to worry about them. */
1137          if(result->tm_year >= 1970)
1138                {
1139                  PRInt64 usec_per_sec;
1140
1141                  localTime.tm_sec = result->tm_sec;
1142                  localTime.tm_min = result->tm_min;
1143                  localTime.tm_hour = result->tm_hour;
1144                  localTime.tm_mday = result->tm_mday;
1145                  localTime.tm_mon = result->tm_month;
1146                  localTime.tm_year = result->tm_year - 1900;
1147                  /* Set this to -1 to tell mktime "I don't care".  If you set
1148                     it to 0 or 1, you are making assertions about whether the
1149                     date you are handing it is in daylight savings mode or not;
1150                     and if you're wrong, it will "fix" it for you. */
1151                  localTime.tm_isdst = -1;
1152
1153#if _MSC_VER == 1400  /* 1400 = Visual C++ 2005 (8.0) */
1154                  /*
1155                   * mktime will return (time_t) -1 if the input is a date
1156                   * after 23:59:59, December 31, 3000, US Pacific Time (not
1157                   * UTC as documented):
1158                   * http://msdn.microsoft.com/en-us/library/d1y53h2a(VS.80).aspx
1159                   * But if the year is 3001, mktime also invokes the invalid
1160                   * parameter handler, causing the application to crash.  This
1161                   * problem has been reported in
1162                   * http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=266036.
1163                   * We avoid this crash by not calling mktime if the date is
1164                   * out of range.  To use a simple test that works in any time
1165                   * zone, we consider year 3000 out of range as well.  (See
1166                   * bug 480740.)
1167                   */
1168                  if (result->tm_year >= 3000) {
1169                      /* Emulate what mktime would have done. */
1170                      errno = EINVAL;
1171                      secs = (time_t) -1;
1172                  } else {
1173                      secs = mktime(&localTime);
1174                  }
1175#else
1176                  secs = mktime(&localTime);
1177#endif
1178                  if (secs != (time_t) -1)
1179                    {
1180                      PRTime usecs64;
1181                      LL_I2L(usecs64, secs);
1182                      LL_I2L(usec_per_sec, PR_USEC_PER_SEC);
1183                      LL_MUL(usecs64, usecs64, usec_per_sec);
1184                      *result_imploded = usecs64;
1185                      return PR_SUCCESS;
1186                    }
1187                }
1188
1189                /* So mktime() can't handle this case.  We assume the
1190                   zone_offset for the date we are parsing is the same as
1191                   the zone offset on 00:00:00 2 Jan 1970 GMT. */
1192                secs = 86400;
1193                localtime_r(&secs, &localTime);
1194                zone_offset = localTime.tm_min
1195                              + 60 * localTime.tm_hour
1196                              + 1440 * (localTime.tm_mday - 2);
1197        }
1198
1199  result->tm_params.tp_gmt_offset = zone_offset * 60;
1200  result->tm_params.tp_dst_offset = dst_offset * 60;
1201
1202  *result_imploded = PR_ImplodeTime(result);
1203  return PR_SUCCESS;
1204}
1205