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

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

2009-07-15 Yong Li <[email protected]>

Reviewed by George Staikos.

https://bugs.webkit.org/show_bug.cgi?id=27020
msToGregorianDateTime should set utcOffset to 0 when outputIsUTC is false

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