• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3  * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
4  * Copyright (C) 2009 Google Inc. All rights reserved.
5  * Copyright (C) 2007-2009 Torch Mobile, Inc.
6  *
7  * The Original Code is Mozilla Communicator client code, released
8  * March 31, 1998.
9  *
10  * The Initial Developer of the Original Code is
11  * Netscape Communications Corporation.
12  * Portions created by the Initial Developer are Copyright (C) 1998
13  * the Initial Developer. All Rights Reserved.
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28  *
29  * Alternatively, the contents of this file may be used under the terms
30  * of either the Mozilla Public License Version 1.1, found at
31  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
32  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
33  * (the "GPL"), in which case the provisions of the MPL or the GPL are
34  * applicable instead of those above.  If you wish to allow use of your
35  * version of this file only under the terms of one of those two
36  * licenses (the MPL or the GPL) and not to allow others to use your
37  * version of this file under the LGPL, indicate your decision by
38  * deletingthe provisions above and replace them with the notice and
39  * other provisions required by the MPL or the GPL, as the case may be.
40  * If you do not delete the provisions above, a recipient may use your
41  * version of this file under any of the LGPL, the MPL or the GPL.
42  */
43 
44 #include "config.h"
45 #include "DateMath.h"
46 
47 #include "Assertions.h"
48 #include "ASCIICType.h"
49 #include "CurrentTime.h"
50 #include "MathExtras.h"
51 #include "StringExtras.h"
52 
53 #include <algorithm>
54 #include <limits.h>
55 #include <limits>
56 #include <stdint.h>
57 #include <time.h>
58 
59 
60 #if HAVE(ERRNO_H)
61 #include <errno.h>
62 #endif
63 
64 #if PLATFORM(DARWIN)
65 #include <notify.h>
66 #endif
67 
68 #if PLATFORM(WINCE) && !PLATFORM(QT)
69 extern "C" size_t strftime(char * const s, const size_t maxsize, const char * const format, const struct tm * const t);
70 extern "C" struct tm * localtime(const time_t *timer);
71 #endif
72 
73 #if HAVE(SYS_TIME_H)
74 #include <sys/time.h>
75 #endif
76 
77 #if HAVE(SYS_TIMEB_H)
78 #include <sys/timeb.h>
79 #endif
80 
81 #define NaN std::numeric_limits<double>::quiet_NaN()
82 
83 namespace WTF {
84 
85 /* Constants */
86 
87 static const double minutesPerDay = 24.0 * 60.0;
88 static const double secondsPerDay = 24.0 * 60.0 * 60.0;
89 static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
90 
91 static const double usecPerSec = 1000000.0;
92 
93 static const double maxUnixTime = 2145859200.0; // 12/31/2037
94 
95 // Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
96 // First for non-leap years, then for leap years.
97 static const int firstDayOfMonth[2][12] = {
98     {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
99     {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
100 };
101 
isLeapYear(int year)102 static inline bool isLeapYear(int year)
103 {
104     if (year % 4 != 0)
105         return false;
106     if (year % 400 == 0)
107         return true;
108     if (year % 100 == 0)
109         return false;
110     return true;
111 }
112 
daysInYear(int year)113 static inline int daysInYear(int year)
114 {
115     return 365 + isLeapYear(year);
116 }
117 
daysFrom1970ToYear(int year)118 static inline double daysFrom1970ToYear(int year)
119 {
120     // The Gregorian Calendar rules for leap years:
121     // Every fourth year is a leap year.  2004, 2008, and 2012 are leap years.
122     // However, every hundredth year is not a leap year.  1900 and 2100 are not leap years.
123     // Every four hundred years, there's a leap year after all.  2000 and 2400 are leap years.
124 
125     static const int leapDaysBefore1971By4Rule = 1970 / 4;
126     static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
127     static const int leapDaysBefore1971By400Rule = 1970 / 400;
128 
129     const double yearMinusOne = year - 1;
130     const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
131     const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
132     const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
133 
134     return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
135 }
136 
msToDays(double ms)137 static inline double msToDays(double ms)
138 {
139     return floor(ms / msPerDay);
140 }
141 
msToYear(double ms)142 static inline int msToYear(double ms)
143 {
144     int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
145     double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
146     if (msFromApproxYearTo1970 > ms)
147         return approxYear - 1;
148     if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
149         return approxYear + 1;
150     return approxYear;
151 }
152 
dayInYear(double ms,int year)153 static inline int dayInYear(double ms, int year)
154 {
155     return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
156 }
157 
msToMilliseconds(double ms)158 static inline double msToMilliseconds(double ms)
159 {
160     double result = fmod(ms, msPerDay);
161     if (result < 0)
162         result += msPerDay;
163     return result;
164 }
165 
166 // 0: Sunday, 1: Monday, etc.
msToWeekDay(double ms)167 static inline int msToWeekDay(double ms)
168 {
169     int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
170     if (wd < 0)
171         wd += 7;
172     return wd;
173 }
174 
msToSeconds(double ms)175 static inline int msToSeconds(double ms)
176 {
177     double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
178     if (result < 0)
179         result += secondsPerMinute;
180     return static_cast<int>(result);
181 }
182 
msToMinutes(double ms)183 static inline int msToMinutes(double ms)
184 {
185     double result = fmod(floor(ms / msPerMinute), minutesPerHour);
186     if (result < 0)
187         result += minutesPerHour;
188     return static_cast<int>(result);
189 }
190 
msToHours(double ms)191 static inline int msToHours(double ms)
192 {
193     double result = fmod(floor(ms/msPerHour), hoursPerDay);
194     if (result < 0)
195         result += hoursPerDay;
196     return static_cast<int>(result);
197 }
198 
monthFromDayInYear(int dayInYear,bool leapYear)199 static inline int monthFromDayInYear(int dayInYear, bool leapYear)
200 {
201     const int d = dayInYear;
202     int step;
203 
204     if (d < (step = 31))
205         return 0;
206     step += (leapYear ? 29 : 28);
207     if (d < step)
208         return 1;
209     if (d < (step += 31))
210         return 2;
211     if (d < (step += 30))
212         return 3;
213     if (d < (step += 31))
214         return 4;
215     if (d < (step += 30))
216         return 5;
217     if (d < (step += 31))
218         return 6;
219     if (d < (step += 31))
220         return 7;
221     if (d < (step += 30))
222         return 8;
223     if (d < (step += 31))
224         return 9;
225     if (d < (step += 30))
226         return 10;
227     return 11;
228 }
229 
checkMonth(int dayInYear,int & startDayOfThisMonth,int & startDayOfNextMonth,int daysInThisMonth)230 static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
231 {
232     startDayOfThisMonth = startDayOfNextMonth;
233     startDayOfNextMonth += daysInThisMonth;
234     return (dayInYear <= startDayOfNextMonth);
235 }
236 
dayInMonthFromDayInYear(int dayInYear,bool leapYear)237 static inline int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
238 {
239     const int d = dayInYear;
240     int step;
241     int next = 30;
242 
243     if (d <= next)
244         return d + 1;
245     const int daysInFeb = (leapYear ? 29 : 28);
246     if (checkMonth(d, step, next, daysInFeb))
247         return d - step;
248     if (checkMonth(d, step, next, 31))
249         return d - step;
250     if (checkMonth(d, step, next, 30))
251         return d - step;
252     if (checkMonth(d, step, next, 31))
253         return d - step;
254     if (checkMonth(d, step, next, 30))
255         return d - step;
256     if (checkMonth(d, step, next, 31))
257         return d - step;
258     if (checkMonth(d, step, next, 31))
259         return d - step;
260     if (checkMonth(d, step, next, 30))
261         return d - step;
262     if (checkMonth(d, step, next, 31))
263         return d - step;
264     if (checkMonth(d, step, next, 30))
265         return d - step;
266     step = next;
267     return d - step;
268 }
269 
monthToDayInYear(int month,bool isLeapYear)270 static inline int monthToDayInYear(int month, bool isLeapYear)
271 {
272     return firstDayOfMonth[isLeapYear][month];
273 }
274 
timeToMS(double hour,double min,double sec,double ms)275 static inline double timeToMS(double hour, double min, double sec, double ms)
276 {
277     return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
278 }
279 
dateToDayInYear(int year,int month,int day)280 static int dateToDayInYear(int year, int month, int day)
281 {
282     year += month / 12;
283 
284     month %= 12;
285     if (month < 0) {
286         month += 12;
287         --year;
288     }
289 
290     int yearday = static_cast<int>(floor(daysFrom1970ToYear(year)));
291     int monthday = monthToDayInYear(month, isLeapYear(year));
292 
293     return yearday + monthday + day - 1;
294 }
295 
getCurrentUTCTime()296 double getCurrentUTCTime()
297 {
298     return floor(getCurrentUTCTimeWithMicroseconds());
299 }
300 
301 // Returns current time in milliseconds since 1 Jan 1970.
getCurrentUTCTimeWithMicroseconds()302 double getCurrentUTCTimeWithMicroseconds()
303 {
304     return currentTime() * 1000.0;
305 }
306 
getLocalTime(const time_t * localTime,struct tm * localTM)307 void getLocalTime(const time_t* localTime, struct tm* localTM)
308 {
309 #if COMPILER(MSVC7) || COMPILER(MINGW) || PLATFORM(WINCE)
310     *localTM = *localtime(localTime);
311 #elif COMPILER(MSVC)
312     localtime_s(localTM, localTime);
313 #else
314     localtime_r(localTime, localTM);
315 #endif
316 }
317 
318 // There is a hard limit at 2038 that we currently do not have a workaround
319 // for (rdar://problem/5052975).
maximumYearForDST()320 static inline int maximumYearForDST()
321 {
322     return 2037;
323 }
324 
minimumYearForDST()325 static inline int minimumYearForDST()
326 {
327     // Because of the 2038 issue (see maximumYearForDST) if the current year is
328     // greater than the max year minus 27 (2010), we want to use the max year
329     // minus 27 instead, to ensure there is a range of 28 years that all years
330     // can map to.
331     return std::min(msToYear(getCurrentUTCTime()), maximumYearForDST() - 27) ;
332 }
333 
334 /*
335  * Find an equivalent year for the one given, where equivalence is deterined by
336  * the two years having the same leapness and the first day of the year, falling
337  * on the same day of the week.
338  *
339  * This function returns a year between this current year and 2037, however this
340  * function will potentially return incorrect results if the current year is after
341  * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
342  * 2100, (rdar://problem/5055038).
343  */
equivalentYearForDST(int year)344 int equivalentYearForDST(int year)
345 {
346     // It is ok if the cached year is not the current year as long as the rules
347     // for DST did not change between the two years; if they did the app would need
348     // to be restarted.
349     static int minYear = minimumYearForDST();
350     int maxYear = maximumYearForDST();
351 
352     int difference;
353     if (year > maxYear)
354         difference = minYear - year;
355     else if (year < minYear)
356         difference = maxYear - year;
357     else
358         return year;
359 
360     int quotient = difference / 28;
361     int product = (quotient) * 28;
362 
363     year += product;
364     ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
365     return year;
366 }
367 
calculateUTCOffset()368 static int32_t calculateUTCOffset()
369 {
370     time_t localTime = time(0);
371     tm localt;
372     getLocalTime(&localTime, &localt);
373 
374     // Get the difference between this time zone and UTC on the 1st of January of this year.
375     localt.tm_sec = 0;
376     localt.tm_min = 0;
377     localt.tm_hour = 0;
378     localt.tm_mday = 1;
379     localt.tm_mon = 0;
380     // Not setting localt.tm_year!
381     localt.tm_wday = 0;
382     localt.tm_yday = 0;
383     localt.tm_isdst = 0;
384 #if HAVE(TM_GMTOFF)
385     localt.tm_gmtoff = 0;
386 #endif
387 #if HAVE(TM_ZONE)
388     localt.tm_zone = 0;
389 #endif
390 
391 #if HAVE(TIMEGM)
392     time_t utcOffset = timegm(&localt) - mktime(&localt);
393 #else
394     // Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
395     localt.tm_year = 109;
396     time_t utcOffset = 1230768000 - mktime(&localt);
397 #endif
398 
399     return static_cast<int32_t>(utcOffset * 1000);
400 }
401 
402 #if PLATFORM(DARWIN)
403 static int32_t s_cachedUTCOffset; // In milliseconds. An assumption here is that access to an int32_t variable is atomic on platforms that take this code path.
404 static bool s_haveCachedUTCOffset;
405 static int s_notificationToken;
406 #endif
407 
408 /*
409  * Get the difference in milliseconds between this time zone and UTC (GMT)
410  * NOT including DST.
411  */
getUTCOffset()412 double getUTCOffset()
413 {
414 #if PLATFORM(DARWIN)
415     if (s_haveCachedUTCOffset) {
416         int notified;
417         uint32_t status = notify_check(s_notificationToken, &notified);
418         if (status == NOTIFY_STATUS_OK && !notified)
419             return s_cachedUTCOffset;
420     }
421 #endif
422 
423     int32_t utcOffset = calculateUTCOffset();
424 
425 #if PLATFORM(DARWIN)
426     // Theoretically, it is possible that several threads will be executing this code at once, in which case we will have a race condition,
427     // and a newer value may be overwritten. In practice, time zones don't change that often.
428     s_cachedUTCOffset = utcOffset;
429 #endif
430 
431     return utcOffset;
432 }
433 
434 /*
435  * Get the DST offset for the time passed in.  Takes
436  * seconds (not milliseconds) and cannot handle dates before 1970
437  * on some OS'
438  */
getDSTOffsetSimple(double localTimeSeconds,double utcOffset)439 static double getDSTOffsetSimple(double localTimeSeconds, double utcOffset)
440 {
441     if (localTimeSeconds > maxUnixTime)
442         localTimeSeconds = maxUnixTime;
443     else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
444         localTimeSeconds += secondsPerDay;
445 
446     //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
447     double offsetTime = (localTimeSeconds * msPerSecond) + utcOffset;
448 
449     // Offset from UTC but doesn't include DST obviously
450     int offsetHour =  msToHours(offsetTime);
451     int offsetMinute =  msToMinutes(offsetTime);
452 
453     // FIXME: time_t has a potential problem in 2038
454     time_t localTime = static_cast<time_t>(localTimeSeconds);
455 
456     tm localTM;
457     getLocalTime(&localTime, &localTM);
458 
459     double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
460 
461     if (diff < 0)
462         diff += secondsPerDay;
463 
464     return (diff * msPerSecond);
465 }
466 
467 // Get the DST offset, given a time in UTC
getDSTOffset(double ms,double utcOffset)468 static double getDSTOffset(double ms, double utcOffset)
469 {
470     // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
471     // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
472     // standard explicitly dictates that historical information should not be considered when
473     // determining DST. For this reason we shift away from years that localtime can handle but would
474     // return historically accurate information.
475     int year = msToYear(ms);
476     int equivalentYear = equivalentYearForDST(year);
477     if (year != equivalentYear) {
478         bool leapYear = isLeapYear(year);
479         int dayInYearLocal = dayInYear(ms, year);
480         int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
481         int month = monthFromDayInYear(dayInYearLocal, leapYear);
482         int day = dateToDayInYear(equivalentYear, month, dayInMonth);
483         ms = (day * msPerDay) + msToMilliseconds(ms);
484     }
485 
486     return getDSTOffsetSimple(ms / msPerSecond, utcOffset);
487 }
488 
gregorianDateTimeToMS(const GregorianDateTime & t,double milliSeconds,bool inputIsUTC)489 double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
490 {
491     int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
492     double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
493     double result = (day * msPerDay) + ms;
494 
495     if (!inputIsUTC) { // convert to UTC
496         double utcOffset = getUTCOffset();
497         result -= utcOffset;
498         result -= getDSTOffset(result, utcOffset);
499     }
500 
501     return result;
502 }
503 
msToGregorianDateTime(double ms,bool outputIsUTC,GregorianDateTime & tm)504 void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
505 {
506     // input is UTC
507     double dstOff = 0.0;
508     const double utcOff = getUTCOffset();
509 
510     if (!outputIsUTC) {  // convert to local time
511         dstOff = getDSTOffset(ms, utcOff);
512         ms += dstOff + utcOff;
513     }
514 
515     const int year = msToYear(ms);
516     tm.second   =  msToSeconds(ms);
517     tm.minute   =  msToMinutes(ms);
518     tm.hour     =  msToHours(ms);
519     tm.weekDay  =  msToWeekDay(ms);
520     tm.yearDay  =  dayInYear(ms, year);
521     tm.monthDay =  dayInMonthFromDayInYear(tm.yearDay, isLeapYear(year));
522     tm.month    =  monthFromDayInYear(tm.yearDay, isLeapYear(year));
523     tm.year     =  year - 1900;
524     tm.isDST    =  dstOff != 0.0;
525 
526     tm.utcOffset = outputIsUTC ? 0 : static_cast<long>((dstOff + utcOff) / msPerSecond);
527     tm.timeZone = NULL;
528 }
529 
initializeDates()530 void initializeDates()
531 {
532 #ifndef NDEBUG
533     static bool alreadyInitialized;
534     ASSERT(!alreadyInitialized++);
535 #endif
536 
537     equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
538 #if PLATFORM(DARWIN)
539     // Register for a notification whenever the time zone changes.
540     uint32_t status = notify_register_check("com.apple.system.timezone", &s_notificationToken);
541     if (status == NOTIFY_STATUS_OK) {
542         s_cachedUTCOffset = calculateUTCOffset();
543         s_haveCachedUTCOffset = true;
544     }
545 #endif
546 }
547 
ymdhmsToSeconds(long year,int mon,int day,int hour,int minute,int second)548 static inline double ymdhmsToSeconds(long year, int mon, int day, int hour, int minute, int second)
549 {
550     double days = (day - 32075)
551         + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
552         + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
553         - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
554         - 2440588;
555     return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
556 }
557 
558 // We follow the recommendation of RFC 2822 to consider all
559 // obsolete time zones not listed here equivalent to "-0000".
560 static const struct KnownZone {
561 #if !PLATFORM(WIN_OS)
562     const
563 #endif
564         char tzName[4];
565     int tzOffset;
566 } known_zones[] = {
567     { "UT", 0 },
568     { "GMT", 0 },
569     { "EST", -300 },
570     { "EDT", -240 },
571     { "CST", -360 },
572     { "CDT", -300 },
573     { "MST", -420 },
574     { "MDT", -360 },
575     { "PST", -480 },
576     { "PDT", -420 }
577 };
578 
skipSpacesAndComments(const char * & s)579 inline static void skipSpacesAndComments(const char*& s)
580 {
581     int nesting = 0;
582     char ch;
583     while ((ch = *s)) {
584         if (!isASCIISpace(ch)) {
585             if (ch == '(')
586                 nesting++;
587             else if (ch == ')' && nesting > 0)
588                 nesting--;
589             else if (nesting == 0)
590                 break;
591         }
592         s++;
593     }
594 }
595 
596 // returns 0-11 (Jan-Dec); -1 on failure
findMonth(const char * monthStr)597 static int findMonth(const char* monthStr)
598 {
599     ASSERT(monthStr);
600     char needle[4];
601     for (int i = 0; i < 3; ++i) {
602         if (!*monthStr)
603             return -1;
604         needle[i] = static_cast<char>(toASCIILower(*monthStr++));
605     }
606     needle[3] = '\0';
607     const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
608     const char *str = strstr(haystack, needle);
609     if (str) {
610         int position = static_cast<int>(str - haystack);
611         if (position % 3 == 0)
612             return position / 3;
613     }
614     return -1;
615 }
616 
parseLong(const char * string,char ** stopPosition,int base,long * result)617 static bool parseLong(const char* string, char** stopPosition, int base, long* result)
618 {
619     *result = strtol(string, stopPosition, base);
620     // Avoid the use of errno as it is not available on Windows CE
621     if (string == *stopPosition || *result == LONG_MIN || *result == LONG_MAX)
622         return false;
623     return true;
624 }
625 
parseDateFromNullTerminatedCharacters(const char * dateString)626 double parseDateFromNullTerminatedCharacters(const char* dateString)
627 {
628     // This parses a date in the form:
629     //     Tuesday, 09-Nov-99 23:12:40 GMT
630     // or
631     //     Sat, 01-Jan-2000 08:00:00 GMT
632     // or
633     //     Sat, 01 Jan 2000 08:00:00 GMT
634     // or
635     //     01 Jan 99 22:00 +0100    (exceptions in rfc822/rfc2822)
636     // ### non RFC formats, added for Javascript:
637     //     [Wednesday] January 09 1999 23:12:40 GMT
638     //     [Wednesday] January 09 23:12:40 GMT 1999
639     //
640     // We ignore the weekday.
641 
642     // Skip leading space
643     skipSpacesAndComments(dateString);
644 
645     long month = -1;
646     const char *wordStart = dateString;
647     // Check contents of first words if not number
648     while (*dateString && !isASCIIDigit(*dateString)) {
649         if (isASCIISpace(*dateString) || *dateString == '(') {
650             if (dateString - wordStart >= 3)
651                 month = findMonth(wordStart);
652             skipSpacesAndComments(dateString);
653             wordStart = dateString;
654         } else
655            dateString++;
656     }
657 
658     // Missing delimiter between month and day (like "January29")?
659     if (month == -1 && wordStart != dateString)
660         month = findMonth(wordStart);
661 
662     skipSpacesAndComments(dateString);
663 
664     if (!*dateString)
665         return NaN;
666 
667     // ' 09-Nov-99 23:12:40 GMT'
668     char* newPosStr;
669     long day;
670     if (!parseLong(dateString, &newPosStr, 10, &day))
671         return NaN;
672     dateString = newPosStr;
673 
674     if (!*dateString)
675         return NaN;
676 
677     if (day < 0)
678         return NaN;
679 
680     long year = 0;
681     if (day > 31) {
682         // ### where is the boundary and what happens below?
683         if (*dateString != '/')
684             return NaN;
685         // looks like a YYYY/MM/DD date
686         if (!*++dateString)
687             return NaN;
688         year = day;
689         if (!parseLong(dateString, &newPosStr, 10, &month))
690             return NaN;
691         month -= 1;
692         dateString = newPosStr;
693         if (*dateString++ != '/' || !*dateString)
694             return NaN;
695         if (!parseLong(dateString, &newPosStr, 10, &day))
696             return NaN;
697         dateString = newPosStr;
698     } else if (*dateString == '/' && month == -1) {
699         dateString++;
700         // This looks like a MM/DD/YYYY date, not an RFC date.
701         month = day - 1; // 0-based
702         if (!parseLong(dateString, &newPosStr, 10, &day))
703             return NaN;
704         if (day < 1 || day > 31)
705             return NaN;
706         dateString = newPosStr;
707         if (*dateString == '/')
708             dateString++;
709         if (!*dateString)
710             return NaN;
711      } else {
712         if (*dateString == '-')
713             dateString++;
714 
715         skipSpacesAndComments(dateString);
716 
717         if (*dateString == ',')
718             dateString++;
719 
720         if (month == -1) { // not found yet
721             month = findMonth(dateString);
722             if (month == -1)
723                 return NaN;
724 
725             while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
726                 dateString++;
727 
728             if (!*dateString)
729                 return NaN;
730 
731             // '-99 23:12:40 GMT'
732             if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
733                 return NaN;
734             dateString++;
735         }
736     }
737 
738     if (month < 0 || month > 11)
739         return NaN;
740 
741     // '99 23:12:40 GMT'
742     if (year <= 0 && *dateString) {
743         if (!parseLong(dateString, &newPosStr, 10, &year))
744             return NaN;
745     }
746 
747     // Don't fail if the time is missing.
748     long hour = 0;
749     long minute = 0;
750     long second = 0;
751     if (!*newPosStr)
752         dateString = newPosStr;
753     else {
754         // ' 23:12:40 GMT'
755         if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
756             if (*newPosStr != ':')
757                 return NaN;
758             // There was no year; the number was the hour.
759             year = -1;
760         } else {
761             // in the normal case (we parsed the year), advance to the next number
762             dateString = ++newPosStr;
763             skipSpacesAndComments(dateString);
764         }
765 
766         parseLong(dateString, &newPosStr, 10, &hour);
767         // Do not check for errno here since we want to continue
768         // even if errno was set becasue we are still looking
769         // for the timezone!
770 
771         // Read a number? If not, this might be a timezone name.
772         if (newPosStr != dateString) {
773             dateString = newPosStr;
774 
775             if (hour < 0 || hour > 23)
776                 return NaN;
777 
778             if (!*dateString)
779                 return NaN;
780 
781             // ':12:40 GMT'
782             if (*dateString++ != ':')
783                 return NaN;
784 
785             if (!parseLong(dateString, &newPosStr, 10, &minute))
786                 return NaN;
787             dateString = newPosStr;
788 
789             if (minute < 0 || minute > 59)
790                 return NaN;
791 
792             // ':40 GMT'
793             if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
794                 return NaN;
795 
796             // seconds are optional in rfc822 + rfc2822
797             if (*dateString ==':') {
798                 dateString++;
799 
800                 if (!parseLong(dateString, &newPosStr, 10, &second))
801                     return NaN;
802                 dateString = newPosStr;
803 
804                 if (second < 0 || second > 59)
805                     return NaN;
806             }
807 
808             skipSpacesAndComments(dateString);
809 
810             if (strncasecmp(dateString, "AM", 2) == 0) {
811                 if (hour > 12)
812                     return NaN;
813                 if (hour == 12)
814                     hour = 0;
815                 dateString += 2;
816                 skipSpacesAndComments(dateString);
817             } else if (strncasecmp(dateString, "PM", 2) == 0) {
818                 if (hour > 12)
819                     return NaN;
820                 if (hour != 12)
821                     hour += 12;
822                 dateString += 2;
823                 skipSpacesAndComments(dateString);
824             }
825         }
826     }
827 
828     bool haveTZ = false;
829     int offset = 0;
830 
831     // Don't fail if the time zone is missing.
832     // Some websites omit the time zone (4275206).
833     if (*dateString) {
834         if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
835             dateString += 3;
836             haveTZ = true;
837         }
838 
839         if (*dateString == '+' || *dateString == '-') {
840             long o;
841             if (!parseLong(dateString, &newPosStr, 10, &o))
842                 return NaN;
843             dateString = newPosStr;
844 
845             if (o < -9959 || o > 9959)
846                 return NaN;
847 
848             int sgn = (o < 0) ? -1 : 1;
849             o = labs(o);
850             if (*dateString != ':') {
851                 offset = ((o / 100) * 60 + (o % 100)) * sgn;
852             } else { // GMT+05:00
853                 long o2;
854                 if (!parseLong(dateString, &newPosStr, 10, &o2))
855                     return NaN;
856                 dateString = newPosStr;
857                 offset = (o * 60 + o2) * sgn;
858             }
859             haveTZ = true;
860         } else {
861             for (int i = 0; i < int(sizeof(known_zones) / sizeof(KnownZone)); i++) {
862                 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
863                     offset = known_zones[i].tzOffset;
864                     dateString += strlen(known_zones[i].tzName);
865                     haveTZ = true;
866                     break;
867                 }
868             }
869         }
870     }
871 
872     skipSpacesAndComments(dateString);
873 
874     if (*dateString && year == -1) {
875         if (!parseLong(dateString, &newPosStr, 10, &year))
876             return NaN;
877         dateString = newPosStr;
878     }
879 
880     skipSpacesAndComments(dateString);
881 
882     // Trailing garbage
883     if (*dateString)
884         return NaN;
885 
886     // Y2K: Handle 2 digit years.
887     if (year >= 0 && year < 100) {
888         if (year < 50)
889             year += 2000;
890         else
891             year += 1900;
892     }
893 
894     // fall back to local timezone
895     if (!haveTZ) {
896         GregorianDateTime t;
897         t.monthDay = day;
898         t.month = month;
899         t.year = year - 1900;
900         t.isDST = -1;
901         t.second = second;
902         t.minute = minute;
903         t.hour = hour;
904 
905         // Use our gregorianDateTimeToMS() rather than mktime() as the latter can't handle the full year range.
906         return gregorianDateTimeToMS(t, 0, false);
907     }
908 
909     return (ymdhmsToSeconds(year, month + 1, day, hour, minute, second) - (offset * 60.0)) * msPerSecond;
910 }
911 
timeClip(double t)912 double timeClip(double t)
913 {
914     if (!isfinite(t))
915         return NaN;
916     if (fabs(t) > 8.64E15)
917         return NaN;
918     return trunc(t);
919 }
920 
921 
922 } // namespace WTF
923