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