source: webkit/trunk/JavaScriptCore/wtf/DateMath.cpp@ 50591

Last change on this file since 50591 was 50591, checked in by [email protected], 16 years ago

Rolled out r50590 because it doesn't build on Windows.

  • Property svn:eol-style set to native
File size: 27.1 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
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)
69extern "C" size_t strftime(char * const s, const size_t maxsize, const char * const format, const struct tm * const t);
70extern "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
83namespace WTF {
84
85/* Constants */
86
87static const double minutesPerDay = 24.0 * 60.0;
88static const double secondsPerDay = 24.0 * 60.0 * 60.0;
89static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
90
91static const double usecPerSec = 1000000.0;
92
93static 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.
97static 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
102static 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
113static inline int daysInYear(int year)
114{
115 return 365 + isLeapYear(year);
116}
117
118static 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
137static inline double msToDays(double ms)
138{
139 return floor(ms / msPerDay);
140}
141
142static 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
153static inline int dayInYear(double ms, int year)
154{
155 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
156}
157
158static 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.
167static 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
175static 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
183static 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
191static 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
199static 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
230static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
231{
232 startDayOfThisMonth = startDayOfNextMonth;
233 startDayOfNextMonth += daysInThisMonth;
234 return (dayInYear <= startDayOfNextMonth);
235}
236
237static 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
270static inline int monthToDayInYear(int month, bool isLeapYear)
271{
272 return firstDayOfMonth[isLeapYear][month];
273}
274
275static inline double timeToMS(double hour, double min, double sec, double ms)
276{
277 return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
278}
279
280static 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
296double getCurrentUTCTime()
297{
298 return floor(getCurrentUTCTimeWithMicroseconds());
299}
300
301// Returns current time in milliseconds since 1 Jan 1970.
302double getCurrentUTCTimeWithMicroseconds()
303{
304 return currentTime() * 1000.0;
305}
306
307void 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).
320static inline int maximumYearForDST()
321{
322 return 2037;
323}
324
325static 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 */
344int 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
368static 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)
403static 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.
404static bool s_haveCachedUTCOffset;
405static 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 */
412double 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 */
439static 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
468static 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
489double 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
504// input is UTC
505void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
506{
507 double dstOff = 0.0;
508 double utcOff = 0.0;
509 if (!outputIsUTC) {
510 utcOff = getUTCOffset();
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 tm.utcOffset = static_cast<long>((dstOff + utcOff) / msPerSecond);
526 tm.timeZone = NULL;
527}
528
529void initializeDates()
530{
531#ifndef NDEBUG
532 static bool alreadyInitialized;
533 ASSERT(!alreadyInitialized++);
534#endif
535
536 equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
537#if PLATFORM(DARWIN)
538 // Register for a notification whenever the time zone changes.
539 uint32_t status = notify_register_check("com.apple.system.timezone", &s_notificationToken);
540 if (status == NOTIFY_STATUS_OK) {
541 s_cachedUTCOffset = calculateUTCOffset();
542 s_haveCachedUTCOffset = true;
543 }
544#endif
545}
546
547static inline double ymdhmsToSeconds(long year, int mon, int day, int hour, int minute, int second)
548{
549 double days = (day - 32075)
550 + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
551 + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
552 - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
553 - 2440588;
554 return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
555}
556
557// We follow the recommendation of RFC 2822 to consider all
558// obsolete time zones not listed here equivalent to "-0000".
559static const struct KnownZone {
560#if !PLATFORM(WIN_OS)
561 const
562#endif
563 char tzName[4];
564 int tzOffset;
565} known_zones[] = {
566 { "UT", 0 },
567 { "GMT", 0 },
568 { "EST", -300 },
569 { "EDT", -240 },
570 { "CST", -360 },
571 { "CDT", -300 },
572 { "MST", -420 },
573 { "MDT", -360 },
574 { "PST", -480 },
575 { "PDT", -420 }
576};
577
578inline static void skipSpacesAndComments(const char*& s)
579{
580 int nesting = 0;
581 char ch;
582 while ((ch = *s)) {
583 if (!isASCIISpace(ch)) {
584 if (ch == '(')
585 nesting++;
586 else if (ch == ')' && nesting > 0)
587 nesting--;
588 else if (nesting == 0)
589 break;
590 }
591 s++;
592 }
593}
594
595// returns 0-11 (Jan-Dec); -1 on failure
596static int findMonth(const char* monthStr)
597{
598 ASSERT(monthStr);
599 char needle[4];
600 for (int i = 0; i < 3; ++i) {
601 if (!*monthStr)
602 return -1;
603 needle[i] = static_cast<char>(toASCIILower(*monthStr++));
604 }
605 needle[3] = '\0';
606 const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
607 const char *str = strstr(haystack, needle);
608 if (str) {
609 int position = static_cast<int>(str - haystack);
610 if (position % 3 == 0)
611 return position / 3;
612 }
613 return -1;
614}
615
616static bool parseLong(const char* string, char** stopPosition, int base, long* result)
617{
618 *result = strtol(string, stopPosition, base);
619 // Avoid the use of errno as it is not available on Windows CE
620 if (string == *stopPosition || *result == LONG_MIN || *result == LONG_MAX)
621 return false;
622 return true;
623}
624
625double parseDateFromNullTerminatedCharacters(const char* dateString)
626{
627 // This parses a date in the form:
628 // Tuesday, 09-Nov-99 23:12:40 GMT
629 // or
630 // Sat, 01-Jan-2000 08:00:00 GMT
631 // or
632 // Sat, 01 Jan 2000 08:00:00 GMT
633 // or
634 // 01 Jan 99 22:00 +0100 (exceptions in rfc822/rfc2822)
635 // ### non RFC formats, added for Javascript:
636 // [Wednesday] January 09 1999 23:12:40 GMT
637 // [Wednesday] January 09 23:12:40 GMT 1999
638 //
639 // We ignore the weekday.
640
641 // Skip leading space
642 skipSpacesAndComments(dateString);
643
644 long month = -1;
645 const char *wordStart = dateString;
646 // Check contents of first words if not number
647 while (*dateString && !isASCIIDigit(*dateString)) {
648 if (isASCIISpace(*dateString) || *dateString == '(') {
649 if (dateString - wordStart >= 3)
650 month = findMonth(wordStart);
651 skipSpacesAndComments(dateString);
652 wordStart = dateString;
653 } else
654 dateString++;
655 }
656
657 // Missing delimiter between month and day (like "January29")?
658 if (month == -1 && wordStart != dateString)
659 month = findMonth(wordStart);
660
661 skipSpacesAndComments(dateString);
662
663 if (!*dateString)
664 return NaN;
665
666 // ' 09-Nov-99 23:12:40 GMT'
667 char* newPosStr;
668 long day;
669 if (!parseLong(dateString, &newPosStr, 10, &day))
670 return NaN;
671 dateString = newPosStr;
672
673 if (!*dateString)
674 return NaN;
675
676 if (day < 0)
677 return NaN;
678
679 long year = 0;
680 if (day > 31) {
681 // ### where is the boundary and what happens below?
682 if (*dateString != '/')
683 return NaN;
684 // looks like a YYYY/MM/DD date
685 if (!*++dateString)
686 return NaN;
687 year = day;
688 if (!parseLong(dateString, &newPosStr, 10, &month))
689 return NaN;
690 month -= 1;
691 dateString = newPosStr;
692 if (*dateString++ != '/' || !*dateString)
693 return NaN;
694 if (!parseLong(dateString, &newPosStr, 10, &day))
695 return NaN;
696 dateString = newPosStr;
697 } else if (*dateString == '/' && month == -1) {
698 dateString++;
699 // This looks like a MM/DD/YYYY date, not an RFC date.
700 month = day - 1; // 0-based
701 if (!parseLong(dateString, &newPosStr, 10, &day))
702 return NaN;
703 if (day < 1 || day > 31)
704 return NaN;
705 dateString = newPosStr;
706 if (*dateString == '/')
707 dateString++;
708 if (!*dateString)
709 return NaN;
710 } else {
711 if (*dateString == '-')
712 dateString++;
713
714 skipSpacesAndComments(dateString);
715
716 if (*dateString == ',')
717 dateString++;
718
719 if (month == -1) { // not found yet
720 month = findMonth(dateString);
721 if (month == -1)
722 return NaN;
723
724 while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
725 dateString++;
726
727 if (!*dateString)
728 return NaN;
729
730 // '-99 23:12:40 GMT'
731 if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
732 return NaN;
733 dateString++;
734 }
735 }
736
737 if (month < 0 || month > 11)
738 return NaN;
739
740 // '99 23:12:40 GMT'
741 if (year <= 0 && *dateString) {
742 if (!parseLong(dateString, &newPosStr, 10, &year))
743 return NaN;
744 }
745
746 // Don't fail if the time is missing.
747 long hour = 0;
748 long minute = 0;
749 long second = 0;
750 if (!*newPosStr)
751 dateString = newPosStr;
752 else {
753 // ' 23:12:40 GMT'
754 if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
755 if (*newPosStr != ':')
756 return NaN;
757 // There was no year; the number was the hour.
758 year = -1;
759 } else {
760 // in the normal case (we parsed the year), advance to the next number
761 dateString = ++newPosStr;
762 skipSpacesAndComments(dateString);
763 }
764
765 parseLong(dateString, &newPosStr, 10, &hour);
766 // Do not check for errno here since we want to continue
767 // even if errno was set becasue we are still looking
768 // for the timezone!
769
770 // Read a number? If not, this might be a timezone name.
771 if (newPosStr != dateString) {
772 dateString = newPosStr;
773
774 if (hour < 0 || hour > 23)
775 return NaN;
776
777 if (!*dateString)
778 return NaN;
779
780 // ':12:40 GMT'
781 if (*dateString++ != ':')
782 return NaN;
783
784 if (!parseLong(dateString, &newPosStr, 10, &minute))
785 return NaN;
786 dateString = newPosStr;
787
788 if (minute < 0 || minute > 59)
789 return NaN;
790
791 // ':40 GMT'
792 if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
793 return NaN;
794
795 // seconds are optional in rfc822 + rfc2822
796 if (*dateString ==':') {
797 dateString++;
798
799 if (!parseLong(dateString, &newPosStr, 10, &second))
800 return NaN;
801 dateString = newPosStr;
802
803 if (second < 0 || second > 59)
804 return NaN;
805 }
806
807 skipSpacesAndComments(dateString);
808
809 if (strncasecmp(dateString, "AM", 2) == 0) {
810 if (hour > 12)
811 return NaN;
812 if (hour == 12)
813 hour = 0;
814 dateString += 2;
815 skipSpacesAndComments(dateString);
816 } else if (strncasecmp(dateString, "PM", 2) == 0) {
817 if (hour > 12)
818 return NaN;
819 if (hour != 12)
820 hour += 12;
821 dateString += 2;
822 skipSpacesAndComments(dateString);
823 }
824 }
825 }
826
827 bool haveTZ = false;
828 int offset = 0;
829
830 // Don't fail if the time zone is missing.
831 // Some websites omit the time zone (4275206).
832 if (*dateString) {
833 if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
834 dateString += 3;
835 haveTZ = true;
836 }
837
838 if (*dateString == '+' || *dateString == '-') {
839 long o;
840 if (!parseLong(dateString, &newPosStr, 10, &o))
841 return NaN;
842 dateString = newPosStr;
843
844 if (o < -9959 || o > 9959)
845 return NaN;
846
847 int sgn = (o < 0) ? -1 : 1;
848 o = labs(o);
849 if (*dateString != ':') {
850 offset = ((o / 100) * 60 + (o % 100)) * sgn;
851 } else { // GMT+05:00
852 long o2;
853 if (!parseLong(dateString, &newPosStr, 10, &o2))
854 return NaN;
855 dateString = newPosStr;
856 offset = (o * 60 + o2) * sgn;
857 }
858 haveTZ = true;
859 } else {
860 for (int i = 0; i < int(sizeof(known_zones) / sizeof(KnownZone)); i++) {
861 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
862 offset = known_zones[i].tzOffset;
863 dateString += strlen(known_zones[i].tzName);
864 haveTZ = true;
865 break;
866 }
867 }
868 }
869 }
870
871 skipSpacesAndComments(dateString);
872
873 if (*dateString && year == -1) {
874 if (!parseLong(dateString, &newPosStr, 10, &year))
875 return NaN;
876 dateString = newPosStr;
877 }
878
879 skipSpacesAndComments(dateString);
880
881 // Trailing garbage
882 if (*dateString)
883 return NaN;
884
885 // Y2K: Handle 2 digit years.
886 if (year >= 0 && year < 100) {
887 if (year < 50)
888 year += 2000;
889 else
890 year += 1900;
891 }
892
893 // fall back to local timezone
894 if (!haveTZ) {
895 GregorianDateTime t;
896 t.monthDay = day;
897 t.month = month;
898 t.year = year - 1900;
899 t.isDST = -1;
900 t.second = second;
901 t.minute = minute;
902 t.hour = hour;
903
904 // Use our gregorianDateTimeToMS() rather than mktime() as the latter can't handle the full year range.
905 return gregorianDateTimeToMS(t, 0, false);
906 }
907
908 return (ymdhmsToSeconds(year, month + 1, day, hour, minute, second) - (offset * 60.0)) * msPerSecond;
909}
910
911double timeClip(double t)
912{
913 if (!isfinite(t))
914 return NaN;
915 if (fabs(t) > 8.64E15)
916 return NaN;
917 return trunc(t);
918}
919
920
921} // namespace WTF
Note: See TracBrowser for help on using the repository browser.