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  * Copyright (C) 2010 &yet, LLC. (nate@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 <stdint.h>
  86 #include <time.h>
  87 #include <wtf/text/StringBuilder.h>
  88 
  89 #if OS(WINDOWS)
  90 #include <windows.h>
  91 #endif
  92 
  93 #if HAVE(ERRNO_H)
  94 #include <errno.h>
  95 #endif
  96 
  97 #if HAVE(SYS_TIME_H)
  98 #include <sys/time.h>
  99 #endif
 100 
 101 #if HAVE(SYS_TIMEB_H)
 102 #include <sys/timeb.h>
 103 #endif
 104 
 105 using namespace WTF;
 106 
 107 namespace WTF {
 108 
 109 /* Constants */
 110 
 111 static const double maxUnixTime = 2145859200.0; // 12/31/2037
 112 // ECMAScript asks not to support for a date of which total
 113 // millisecond value is larger than the following value.
 114 // See 15.9.1.14 of ECMA-262 5th edition.
 115 static const double maxECMAScriptTime = 8.64E15;
 116 
 117 // Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
 118 // First for non-leap years, then for leap years.
 119 static const int firstDayOfMonth[2][12] = {
 120     {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
 121     {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
 122 };
 123 
 124 #if !OS(WINCE)
 125 static inline void getLocalTime(const time_t* localTime, struct tm* localTM)
 126 {
 127 #if COMPILER(MINGW)
 128     *localTM = *localtime(localTime);
 129 #elif COMPILER(MSVC)
 130     localtime_s(localTM, localTime);
 131 #else
 132     localtime_r(localTime, localTM);
 133 #endif
 134 }
 135 #endif
 136 
 137 bool isLeapYear(int year)
 138 {
 139     if (year % 4 != 0)
 140         return false;
 141     if (year % 400 == 0)
 142         return true;
 143     if (year % 100 == 0)
 144         return false;
 145     return true;
 146 }
 147 
 148 static inline int daysInYear(int year)
 149 {
 150     return 365 + isLeapYear(year);
 151 }
 152 
 153 static inline double daysFrom1970ToYear(int year)
 154 {
 155     // The Gregorian Calendar rules for leap years:
 156     // Every fourth year is a leap year.  2004, 2008, and 2012 are leap years.
 157     // However, every hundredth year is not a leap year.  1900 and 2100 are not leap years.
 158     // Every four hundred years, there's a leap year after all.  2000 and 2400 are leap years.
 159 
 160     static const int leapDaysBefore1971By4Rule = 1970 / 4;
 161     static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
 162     static const int leapDaysBefore1971By400Rule = 1970 / 400;
 163 
 164     const double yearMinusOne = year - 1;
 165     const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
 166     const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
 167     const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
 168 
 169     return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
 170 }
 171 
 172 double msToDays(double ms)
 173 {
 174     return floor(ms / msPerDay);
 175 }
 176 
 177 static void appendTwoDigitNumber(StringBuilder& builder, int number)
 178 {
 179     ASSERT(number >= 0);
 180     ASSERT(number < 100);
 181     builder.append(static_cast<LChar>('0' + number / 10));
 182     builder.append(static_cast<LChar>('0' + number % 10));
 183 }
 184 
 185 int msToYear(double ms)
 186 {
 187     int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
 188     double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
 189     if (msFromApproxYearTo1970 > ms)
 190         return approxYear - 1;
 191     if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
 192         return approxYear + 1;
 193     return approxYear;
 194 }
 195 
 196 int dayInYear(double ms, int year)
 197 {
 198     return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
 199 }
 200 
 201 static inline double msToMilliseconds(double ms)
 202 {
 203     double result = fmod(ms, msPerDay);
 204     if (result < 0)
 205         result += msPerDay;
 206     return result;
 207 }
 208 
 209 int msToMinutes(double ms)
 210 {
 211     double result = fmod(floor(ms / msPerMinute), minutesPerHour);
 212     if (result < 0)
 213         result += minutesPerHour;
 214     return static_cast<int>(result);
 215 }
 216 
 217 int msToHours(double ms)
 218 {
 219     double result = fmod(floor(ms/msPerHour), hoursPerDay);
 220     if (result < 0)
 221         result += hoursPerDay;
 222     return static_cast<int>(result);
 223 }
 224 
 225 int monthFromDayInYear(int dayInYear, bool leapYear)
 226 {
 227     const int d = dayInYear;
 228     int step;
 229 
 230     if (d < (step = 31))
 231         return 0;
 232     step += (leapYear ? 29 : 28);
 233     if (d < step)
 234         return 1;
 235     if (d < (step += 31))
 236         return 2;
 237     if (d < (step += 30))
 238         return 3;
 239     if (d < (step += 31))
 240         return 4;
 241     if (d < (step += 30))
 242         return 5;
 243     if (d < (step += 31))
 244         return 6;
 245     if (d < (step += 31))
 246         return 7;
 247     if (d < (step += 30))
 248         return 8;
 249     if (d < (step += 31))
 250         return 9;
 251     if (d < (step += 30))
 252         return 10;
 253     return 11;
 254 }
 255 
 256 static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
 257 {
 258     startDayOfThisMonth = startDayOfNextMonth;
 259     startDayOfNextMonth += daysInThisMonth;
 260     return (dayInYear <= startDayOfNextMonth);
 261 }
 262 
 263 int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
 264 {
 265     const int d = dayInYear;
 266     int step;
 267     int next = 30;
 268 
 269     if (d <= next)
 270         return d + 1;
 271     const int daysInFeb = (leapYear ? 29 : 28);
 272     if (checkMonth(d, step, next, daysInFeb))
 273         return d - step;
 274     if (checkMonth(d, step, next, 31))
 275         return d - step;
 276     if (checkMonth(d, step, next, 30))
 277         return d - step;
 278     if (checkMonth(d, step, next, 31))
 279         return d - step;
 280     if (checkMonth(d, step, next, 30))
 281         return d - step;
 282     if (checkMonth(d, step, next, 31))
 283         return d - step;
 284     if (checkMonth(d, step, next, 31))
 285         return d - step;
 286     if (checkMonth(d, step, next, 30))
 287         return d - step;
 288     if (checkMonth(d, step, next, 31))
 289         return d - step;
 290     if (checkMonth(d, step, next, 30))
 291         return d - step;
 292     step = next;
 293     return d - step;
 294 }
 295 
 296 int dayInYear(int year, int month, int day)
 297 {
 298     return firstDayOfMonth[isLeapYear(year)][month] + day - 1;
 299 }
 300 
 301 double dateToDaysFrom1970(int year, int month, int day)
 302 {
 303     year += month / 12;
 304 
 305     month %= 12;
 306     if (month < 0) {
 307         month += 12;
 308         --year;
 309     }
 310 
 311     double yearday = floor(daysFrom1970ToYear(year));
 312     ASSERT((year >= 1970 && yearday >= 0) || (year < 1970 && yearday < 0));
 313     return yearday + dayInYear(year, month, day);
 314 }
 315 
 316 // There is a hard limit at 2038 that we currently do not have a workaround
 317 // for (rdar://problem/5052975).
 318 static inline int maximumYearForDST()
 319 {
 320     return 2037;
 321 }
 322 
 323 static inline int minimumYearForDST()
 324 {
 325     // Because of the 2038 issue (see maximumYearForDST) if the current year is
 326     // greater than the max year minus 27 (2010), we want to use the max year
 327     // minus 27 instead, to ensure there is a range of 28 years that all years
 328     // can map to.
 329     return std::min(msToYear(jsCurrentTime()), maximumYearForDST() - 27) ;
 330 }
 331 
 332 /*
 333  * Find an equivalent year for the one given, where equivalence is deterined by
 334  * the two years having the same leapness and the first day of the year, falling
 335  * on the same day of the week.
 336  *
 337  * This function returns a year between this current year and 2037, however this
 338  * function will potentially return incorrect results if the current year is after
 339  * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
 340  * 2100, (rdar://problem/5055038).
 341  */
 342 int equivalentYearForDST(int year)
 343 {
 344     // It is ok if the cached year is not the current year as long as the rules
 345     // for DST did not change between the two years; if they did the app would need
 346     // to be restarted.
 347     static int minYear = minimumYearForDST();
 348     int maxYear = maximumYearForDST();
 349 
 350     int difference;
 351     if (year > maxYear)
 352         difference = minYear - year;
 353     else if (year < minYear)
 354         difference = maxYear - year;
 355     else
 356         return year;
 357 
 358     int quotient = difference / 28;
 359     int product = (quotient) * 28;
 360 
 361     year += product;
 362     ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(std::numeric_limits<double>::quiet_NaN())));
 363     return year;
 364 }
 365 
 366 #if !HAVE(TM_GMTOFF)
 367 
 368 static int32_t calculateUTCOffset()
 369 {
 370 #if OS(WINDOWS)
 371     TIME_ZONE_INFORMATION timeZoneInformation;
 372     GetTimeZoneInformation(&timeZoneInformation);
 373     int32_t bias = timeZoneInformation.Bias + timeZoneInformation.StandardBias;
 374     return -bias * 60 * 1000;
 375 #else
 376     time_t localTime = time(0);
 377     tm localt;
 378     getLocalTime(&localTime, &localt);
 379 
 380     // Get the difference between this time zone and UTC on the 1st of January of this year.
 381     localt.tm_sec = 0;
 382     localt.tm_min = 0;
 383     localt.tm_hour = 0;
 384     localt.tm_mday = 1;
 385     localt.tm_mon = 0;
 386     // Not setting localt.tm_year!
 387     localt.tm_wday = 0;
 388     localt.tm_yday = 0;
 389     localt.tm_isdst = 0;
 390 #if HAVE(TM_GMTOFF)
 391     localt.tm_gmtoff = 0;
 392 #endif
 393 #if HAVE(TM_ZONE)
 394     localt.tm_zone = 0;
 395 #endif
 396 
 397 #if HAVE(TIMEGM)
 398     time_t utcOffset = timegm(&localt) - mktime(&localt);
 399 #else
 400     // Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
 401     localt.tm_year = 109;
 402     time_t utcOffset = 1230768000 - mktime(&localt);
 403 #endif
 404 
 405     return static_cast<int32_t>(utcOffset * 1000);
 406 #endif
 407 }
 408 
 409 #if OS(WINDOWS)
 410 // Code taken from http://support.microsoft.com/kb/167296
 411 static void UnixTimeToFileTime(time_t t, LPFILETIME pft)
 412 {
 413     // Note that LONGLONG is a 64-bit value
 414     LONGLONG ll;
 415 
 416     ll = Int32x32To64(t, 10000000) + 116444736000000000;
 417     pft->dwLowDateTime = (DWORD)ll;
 418     pft->dwHighDateTime = ll >> 32;
 419 }
 420 #endif
 421 
 422 /*
 423  * Get the DST offset for the time passed in.
 424  */
 425 static double calculateDSTOffset(time_t localTime, double utcOffset)
 426 {
 427 #if OS(WINCE)
 428     UNUSED_PARAM(localTime);
 429     UNUSED_PARAM(utcOffset);
 430     return 0;
 431 #elif OS(WINDOWS)
 432     FILETIME utcFileTime;
 433     UnixTimeToFileTime(localTime, &utcFileTime);
 434     SYSTEMTIME utcSystemTime, localSystemTime;
 435     FileTimeToSystemTime(&utcFileTime, &utcSystemTime);
 436     SystemTimeToTzSpecificLocalTime(0, &utcSystemTime, &localSystemTime);
 437 
 438     double offsetTime = (localTime * msPerSecond) + utcOffset;
 439 
 440     // Offset from UTC but doesn't include DST obviously
 441     int offsetHour =  msToHours(offsetTime);
 442     int offsetMinute =  msToMinutes(offsetTime);
 443 
 444     double diff = ((localSystemTime.wHour - offsetHour) * secondsPerHour) + ((localSystemTime.wMinute - offsetMinute) * 60);
 445 
 446 // See: https://bugs.webkit.org/show_bug.cgi?id=137003
 447 #if PLATFORM(JAVA)
 448     if (diff < 0)
 449         diff += secondsPerDay;
 450 #endif
 451 
 452     return diff * msPerSecond;
 453 #else
 454     //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
 455     double offsetTime = (localTime * msPerSecond) + utcOffset;
 456 
 457     // Offset from UTC but doesn't include DST obviously
 458     int offsetHour =  msToHours(offsetTime);
 459     int offsetMinute =  msToMinutes(offsetTime);
 460 
 461     tm localTM;
 462     getLocalTime(&localTime, &localTM);
 463 
 464     double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
 465 
 466     if (diff < 0)
 467         diff += secondsPerDay;
 468 
 469     return (diff * msPerSecond);
 470 #endif
 471 }
 472 
 473 #endif
 474 
 475 // Returns combined offset in millisecond (UTC + DST).
 476 LocalTimeOffset calculateLocalTimeOffset(double ms)
 477 {
 478     // On Mac OS X, the call to localtime (see calculateDSTOffset) will return historically accurate
 479     // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
 480     // standard explicitly dictates that historical information should not be considered when
 481     // determining DST. For this reason we shift away from years that localtime can handle but would
 482     // return historically accurate information.
 483     int year = msToYear(ms);
 484     int equivalentYear = equivalentYearForDST(year);
 485     if (year != equivalentYear) {
 486         bool leapYear = isLeapYear(year);
 487         int dayInYearLocal = dayInYear(ms, year);
 488         int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
 489         int month = monthFromDayInYear(dayInYearLocal, leapYear);
 490         double day = dateToDaysFrom1970(equivalentYear, month, dayInMonth);
 491         ms = (day * msPerDay) + msToMilliseconds(ms);
 492     }
 493 
 494     double localTimeSeconds = ms / msPerSecond;
 495     if (localTimeSeconds > maxUnixTime)
 496         localTimeSeconds = maxUnixTime;
 497     else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0).
 498         localTimeSeconds += secondsPerDay;
 499     // FIXME: time_t has a potential problem in 2038.
 500     time_t localTime = static_cast<time_t>(localTimeSeconds);
 501 
 502 #if HAVE(TM_GMTOFF)
 503     tm localTM;
 504     getLocalTime(&localTime, &localTM);
 505     return LocalTimeOffset(localTM.tm_isdst, localTM.tm_gmtoff * msPerSecond);
 506 #else
 507     double utcOffset = calculateUTCOffset();
 508     double dstOffset = calculateDSTOffset(localTime, utcOffset);
 509     return LocalTimeOffset(dstOffset, utcOffset + dstOffset);
 510 #endif
 511 }
 512 
 513 void initializeDates()
 514 {
 515 #if !ASSERT_DISABLED
 516     static bool alreadyInitialized;
 517     ASSERT(!alreadyInitialized);
 518     alreadyInitialized = true;
 519 #endif
 520 
 521     equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
 522 }
 523 
 524 static inline double ymdhmsToSeconds(int year, long mon, long day, long hour, long minute, double second)
 525 {
 526     double days = (day - 32075)
 527         + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
 528         + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
 529         - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
 530         - 2440588;
 531     return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
 532 }
 533 
 534 // We follow the recommendation of RFC 2822 to consider all
 535 // obsolete time zones not listed here equivalent to "-0000".
 536 static const struct KnownZone {
 537 #if !OS(WINDOWS)
 538     const
 539 #endif
 540         char tzName[4];
 541     int tzOffset;
 542 } known_zones[] = {
 543     { "UT", 0 },
 544     { "GMT", 0 },
 545     { "EST", -300 },
 546     { "EDT", -240 },
 547     { "CST", -360 },
 548     { "CDT", -300 },
 549     { "MST", -420 },
 550     { "MDT", -360 },
 551     { "PST", -480 },
 552     { "PDT", -420 }
 553 };
 554 
 555 inline static void skipSpacesAndComments(const char*& s)
 556 {
 557     int nesting = 0;
 558     char ch;
 559     while ((ch = *s)) {
 560         if (!isASCIISpace(ch)) {
 561             if (ch == '(')
 562                 nesting++;
 563             else if (ch == ')' && nesting > 0)
 564                 nesting--;
 565             else if (nesting == 0)
 566                 break;
 567         }
 568         s++;
 569     }
 570 }
 571 
 572 // returns 0-11 (Jan-Dec); -1 on failure
 573 static int findMonth(const char* monthStr)
 574 {
 575     ASSERT(monthStr);
 576     char needle[4];
 577     for (int i = 0; i < 3; ++i) {
 578         if (!*monthStr)
 579             return -1;
 580         needle[i] = static_cast<char>(toASCIILower(*monthStr++));
 581     }
 582     needle[3] = '\0';
 583     const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
 584     const char *str = strstr(haystack, needle);
 585     if (str) {
 586         int position = static_cast<int>(str - haystack);
 587         if (position % 3 == 0)
 588             return position / 3;
 589     }
 590     return -1;
 591 }
 592 
 593 static bool parseInt(const char* string, char** stopPosition, int base, int* result)
 594 {
 595     long longResult = strtol(string, stopPosition, base);
 596     // Avoid the use of errno as it is not available on Windows CE
 597     if (string == *stopPosition || longResult <= std::numeric_limits<int>::min() || longResult >= std::numeric_limits<int>::max())
 598         return false;
 599     *result = static_cast<int>(longResult);
 600     return true;
 601 }
 602 
 603 static bool parseLong(const char* string, char** stopPosition, int base, long* result)
 604 {
 605     *result = strtol(string, stopPosition, base);
 606     // Avoid the use of errno as it is not available on Windows CE
 607     if (string == *stopPosition || *result == std::numeric_limits<long>::min() || *result == std::numeric_limits<long>::max())
 608         return false;
 609     return true;
 610 }
 611 
 612 // Parses a date with the format YYYY[-MM[-DD]].
 613 // Year parsing is lenient, allows any number of digits, and +/-.
 614 // Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
 615 static char* parseES5DatePortion(const char* currentPosition, int& year, long& month, long& day)
 616 {
 617     char* postParsePosition;
 618 
 619     // This is a bit more lenient on the year string than ES5 specifies:
 620     // instead of restricting to 4 digits (or 6 digits with mandatory +/-),
 621     // it accepts any integer value. Consider this an implementation fallback.
 622     if (!parseInt(currentPosition, &postParsePosition, 10, &year))
 623         return 0;
 624 
 625     // Check for presence of -MM portion.
 626     if (*postParsePosition != '-')
 627         return postParsePosition;
 628     currentPosition = postParsePosition + 1;
 629     
 630     if (!isASCIIDigit(*currentPosition))
 631         return 0;
 632     if (!parseLong(currentPosition, &postParsePosition, 10, &month))
 633         return 0;
 634     if ((postParsePosition - currentPosition) != 2)
 635         return 0;
 636 
 637     // Check for presence of -DD portion.
 638     if (*postParsePosition != '-')
 639         return postParsePosition;
 640     currentPosition = postParsePosition + 1;
 641     
 642     if (!isASCIIDigit(*currentPosition))
 643         return 0;
 644     if (!parseLong(currentPosition, &postParsePosition, 10, &day))
 645         return 0;
 646     if ((postParsePosition - currentPosition) != 2)
 647         return 0;
 648     return postParsePosition;
 649 }
 650 
 651 // Parses a time with the format HH:mm[:ss[.sss]][Z|(+|-)00:00].
 652 // Fractional seconds parsing is lenient, allows any number of digits.
 653 // Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
 654 static char* parseES5TimePortion(char* currentPosition, long& hours, long& minutes, double& seconds, long& timeZoneSeconds)
 655 {
 656     char* postParsePosition;
 657     if (!isASCIIDigit(*currentPosition))
 658         return 0;
 659     if (!parseLong(currentPosition, &postParsePosition, 10, &hours))
 660         return 0;
 661     if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2)
 662         return 0;
 663     currentPosition = postParsePosition + 1;
 664     
 665     if (!isASCIIDigit(*currentPosition))
 666         return 0;
 667     if (!parseLong(currentPosition, &postParsePosition, 10, &minutes))
 668         return 0;
 669     if ((postParsePosition - currentPosition) != 2)
 670         return 0;
 671     currentPosition = postParsePosition;
 672 
 673     // Seconds are optional.
 674     if (*currentPosition == ':') {
 675         ++currentPosition;
 676     
 677         long intSeconds;
 678         if (!isASCIIDigit(*currentPosition))
 679             return 0;
 680         if (!parseLong(currentPosition, &postParsePosition, 10, &intSeconds))
 681             return 0;
 682         if ((postParsePosition - currentPosition) != 2)
 683             return 0;
 684         seconds = intSeconds;
 685         if (*postParsePosition == '.') {
 686             currentPosition = postParsePosition + 1;
 687             
 688             // In ECMA-262-5 it's a bit unclear if '.' can be present without milliseconds, but
 689             // a reasonable interpretation guided by the given examples and RFC 3339 says "no".
 690             // We check the next character to avoid reading +/- timezone hours after an invalid decimal.
 691             if (!isASCIIDigit(*currentPosition))
 692                 return 0;
 693             
 694             // We are more lenient than ES5 by accepting more or less than 3 fraction digits.
 695             long fracSeconds;
 696             if (!parseLong(currentPosition, &postParsePosition, 10, &fracSeconds))
 697                 return 0;
 698             
 699             long numFracDigits = postParsePosition - currentPosition;
 700             seconds += fracSeconds * pow(10.0, static_cast<double>(-numFracDigits));
 701         }
 702         currentPosition = postParsePosition;
 703     }
 704 
 705     if (*currentPosition == 'Z')
 706         return currentPosition + 1;
 707 
 708     bool tzNegative;
 709     if (*currentPosition == '-')
 710         tzNegative = true;
 711     else if (*currentPosition == '+')
 712         tzNegative = false;
 713     else
 714         return currentPosition; // no timezone
 715     ++currentPosition;
 716     
 717     long tzHours;
 718     long tzHoursAbs;
 719     long tzMinutes;
 720     
 721     if (!isASCIIDigit(*currentPosition))
 722         return 0;
 723     if (!parseLong(currentPosition, &postParsePosition, 10, &tzHours))
 724         return 0;
 725     if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2)
 726         return 0;
 727     tzHoursAbs = labs(tzHours);
 728     currentPosition = postParsePosition + 1;
 729     
 730     if (!isASCIIDigit(*currentPosition))
 731         return 0;
 732     if (!parseLong(currentPosition, &postParsePosition, 10, &tzMinutes))
 733         return 0;
 734     if ((postParsePosition - currentPosition) != 2)
 735         return 0;
 736     currentPosition = postParsePosition;
 737     
 738     if (tzHoursAbs > 24)
 739         return 0;
 740     if (tzMinutes < 0 || tzMinutes > 59)
 741         return 0;
 742     
 743     timeZoneSeconds = 60 * (tzMinutes + (60 * tzHoursAbs));
 744     if (tzNegative)
 745         timeZoneSeconds = -timeZoneSeconds;
 746 
 747     return currentPosition;
 748 }
 749 
 750 double parseES5DateFromNullTerminatedCharacters(const char* dateString)
 751 {
 752     // This parses a date of the form defined in ECMA-262-5, section 15.9.1.15
 753     // (similar to RFC 3339 / ISO 8601: YYYY-MM-DDTHH:mm:ss[.sss]Z).
 754     // In most cases it is intentionally strict (e.g. correct field widths, no stray whitespace).
 755     
 756     static const long daysPerMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
 757     
 758     // The year must be present, but the other fields may be omitted - see ES5.1 15.9.1.15.
 759     int year = 0;
 760     long month = 1;
 761     long day = 1;
 762     long hours = 0;
 763     long minutes = 0;
 764     double seconds = 0;
 765     long timeZoneSeconds = 0;
 766 
 767     // Parse the date YYYY[-MM[-DD]]
 768     char* currentPosition = parseES5DatePortion(dateString, year, month, day);
 769     if (!currentPosition)
 770         return std::numeric_limits<double>::quiet_NaN();
 771     // Look for a time portion.
 772     if (*currentPosition == 'T') {
 773         // Parse the time HH:mm[:ss[.sss]][Z|(+|-)00:00]
 774         currentPosition = parseES5TimePortion(currentPosition + 1, hours, minutes, seconds, timeZoneSeconds);
 775         if (!currentPosition)
 776             return std::numeric_limits<double>::quiet_NaN();
 777     }
 778     // Check that we have parsed all characters in the string.
 779     if (*currentPosition)
 780         return std::numeric_limits<double>::quiet_NaN();
 781 
 782     // A few of these checks could be done inline above, but since many of them are interrelated
 783     // we would be sacrificing readability to "optimize" the (presumably less common) failure path.
 784     if (month < 1 || month > 12)
 785         return std::numeric_limits<double>::quiet_NaN();
 786     if (day < 1 || day > daysPerMonth[month - 1])
 787         return std::numeric_limits<double>::quiet_NaN();
 788     if (month == 2 && day > 28 && !isLeapYear(year))
 789         return std::numeric_limits<double>::quiet_NaN();
 790     if (hours < 0 || hours > 24)
 791         return std::numeric_limits<double>::quiet_NaN();
 792     if (hours == 24 && (minutes || seconds))
 793         return std::numeric_limits<double>::quiet_NaN();
 794     if (minutes < 0 || minutes > 59)
 795         return std::numeric_limits<double>::quiet_NaN();
 796     if (seconds < 0 || seconds >= 61)
 797         return std::numeric_limits<double>::quiet_NaN();
 798     if (seconds > 60) {
 799         // Discard leap seconds by clamping to the end of a minute.
 800         seconds = 60;
 801     }
 802         
 803     double dateSeconds = ymdhmsToSeconds(year, month, day, hours, minutes, seconds) - timeZoneSeconds;
 804     return dateSeconds * msPerSecond;
 805 }
 806 
 807 // Odd case where 'exec' is allowed to be 0, to accomodate a caller in WebCore.
 808 double parseDateFromNullTerminatedCharacters(const char* dateString, bool& haveTZ, int& offset)
 809 {
 810     haveTZ = false;
 811     offset = 0;
 812 
 813     // This parses a date in the form:
 814     //     Tuesday, 09-Nov-99 23:12:40 GMT
 815     // or
 816     //     Sat, 01-Jan-2000 08:00:00 GMT
 817     // or
 818     //     Sat, 01 Jan 2000 08:00:00 GMT
 819     // or
 820     //     01 Jan 99 22:00 +0100    (exceptions in rfc822/rfc2822)
 821     // ### non RFC formats, added for Javascript:
 822     //     [Wednesday] January 09 1999 23:12:40 GMT
 823     //     [Wednesday] January 09 23:12:40 GMT 1999
 824     //
 825     // We ignore the weekday.
 826      
 827     // Skip leading space
 828     skipSpacesAndComments(dateString);
 829 
 830     long month = -1;
 831     const char *wordStart = dateString;
 832     // Check contents of first words if not number
 833     while (*dateString && !isASCIIDigit(*dateString)) {
 834         if (isASCIISpace(*dateString) || *dateString == '(') {
 835             if (dateString - wordStart >= 3)
 836                 month = findMonth(wordStart);
 837             skipSpacesAndComments(dateString);
 838             wordStart = dateString;
 839         } else
 840            dateString++;
 841     }
 842 
 843     // Missing delimiter between month and day (like "January29")?
 844     if (month == -1 && wordStart != dateString)
 845         month = findMonth(wordStart);
 846 
 847     skipSpacesAndComments(dateString);
 848 
 849     if (!*dateString)
 850         return std::numeric_limits<double>::quiet_NaN();
 851 
 852     // ' 09-Nov-99 23:12:40 GMT'
 853     char* newPosStr;
 854     long day;
 855     if (!parseLong(dateString, &newPosStr, 10, &day))
 856         return std::numeric_limits<double>::quiet_NaN();
 857     dateString = newPosStr;
 858 
 859     if (!*dateString)
 860         return std::numeric_limits<double>::quiet_NaN();
 861 
 862     if (day < 0)
 863         return std::numeric_limits<double>::quiet_NaN();
 864 
 865     int year = 0;
 866     if (day > 31) {
 867         // ### where is the boundary and what happens below?
 868         if (*dateString != '/')
 869             return std::numeric_limits<double>::quiet_NaN();
 870         // looks like a YYYY/MM/DD date
 871         if (!*++dateString)
 872             return std::numeric_limits<double>::quiet_NaN();
 873         if (day <= std::numeric_limits<int>::min() || day >= std::numeric_limits<int>::max())
 874             return std::numeric_limits<double>::quiet_NaN();
 875         year = static_cast<int>(day);
 876         if (!parseLong(dateString, &newPosStr, 10, &month))
 877             return std::numeric_limits<double>::quiet_NaN();
 878         month -= 1;
 879         dateString = newPosStr;
 880         if (*dateString++ != '/' || !*dateString)
 881             return std::numeric_limits<double>::quiet_NaN();
 882         if (!parseLong(dateString, &newPosStr, 10, &day))
 883             return std::numeric_limits<double>::quiet_NaN();
 884         dateString = newPosStr;
 885     } else if (*dateString == '/' && month == -1) {
 886         dateString++;
 887         // This looks like a MM/DD/YYYY date, not an RFC date.
 888         month = day - 1; // 0-based
 889         if (!parseLong(dateString, &newPosStr, 10, &day))
 890             return std::numeric_limits<double>::quiet_NaN();
 891         if (day < 1 || day > 31)
 892             return std::numeric_limits<double>::quiet_NaN();
 893         dateString = newPosStr;
 894         if (*dateString == '/')
 895             dateString++;
 896         if (!*dateString)
 897             return std::numeric_limits<double>::quiet_NaN();
 898      } else {
 899         if (*dateString == '-')
 900             dateString++;
 901 
 902         skipSpacesAndComments(dateString);
 903 
 904         if (*dateString == ',')
 905             dateString++;
 906 
 907         if (month == -1) { // not found yet
 908             month = findMonth(dateString);
 909             if (month == -1)
 910                 return std::numeric_limits<double>::quiet_NaN();
 911 
 912             while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
 913                 dateString++;
 914 
 915             if (!*dateString)
 916                 return std::numeric_limits<double>::quiet_NaN();
 917 
 918             // '-99 23:12:40 GMT'
 919             if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
 920                 return std::numeric_limits<double>::quiet_NaN();
 921             dateString++;
 922         }
 923     }
 924 
 925     if (month < 0 || month > 11)
 926         return std::numeric_limits<double>::quiet_NaN();
 927 
 928     // '99 23:12:40 GMT'
 929     if (year <= 0 && *dateString) {
 930         if (!parseInt(dateString, &newPosStr, 10, &year))
 931             return std::numeric_limits<double>::quiet_NaN();
 932     }
 933 
 934     // Don't fail if the time is missing.
 935     long hour = 0;
 936     long minute = 0;
 937     long second = 0;
 938     if (!*newPosStr)
 939         dateString = newPosStr;
 940     else {
 941         // ' 23:12:40 GMT'
 942         if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
 943             if (*newPosStr != ':')
 944                 return std::numeric_limits<double>::quiet_NaN();
 945             // There was no year; the number was the hour.
 946             year = -1;
 947         } else {
 948             // in the normal case (we parsed the year), advance to the next number
 949             dateString = ++newPosStr;
 950             skipSpacesAndComments(dateString);
 951         }
 952 
 953         parseLong(dateString, &newPosStr, 10, &hour);
 954         // Do not check for errno here since we want to continue
 955         // even if errno was set becasue we are still looking
 956         // for the timezone!
 957 
 958         // Read a number? If not, this might be a timezone name.
 959         if (newPosStr != dateString) {
 960             dateString = newPosStr;
 961 
 962             if (hour < 0 || hour > 23)
 963                 return std::numeric_limits<double>::quiet_NaN();
 964 
 965             if (!*dateString)
 966                 return std::numeric_limits<double>::quiet_NaN();
 967 
 968             // ':12:40 GMT'
 969             if (*dateString++ != ':')
 970                 return std::numeric_limits<double>::quiet_NaN();
 971 
 972             if (!parseLong(dateString, &newPosStr, 10, &minute))
 973                 return std::numeric_limits<double>::quiet_NaN();
 974             dateString = newPosStr;
 975 
 976             if (minute < 0 || minute > 59)
 977                 return std::numeric_limits<double>::quiet_NaN();
 978 
 979             // ':40 GMT'
 980             if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
 981                 return std::numeric_limits<double>::quiet_NaN();
 982 
 983             // seconds are optional in rfc822 + rfc2822
 984             if (*dateString ==':') {
 985                 dateString++;
 986 
 987                 if (!parseLong(dateString, &newPosStr, 10, &second))
 988                     return std::numeric_limits<double>::quiet_NaN();
 989                 dateString = newPosStr;
 990 
 991                 if (second < 0 || second > 59)
 992                     return std::numeric_limits<double>::quiet_NaN();
 993             }
 994 
 995             skipSpacesAndComments(dateString);
 996 
 997             if (strncasecmp(dateString, "AM", 2) == 0) {
 998                 if (hour > 12)
 999                     return std::numeric_limits<double>::quiet_NaN();
1000                 if (hour == 12)
1001                     hour = 0;
1002                 dateString += 2;
1003                 skipSpacesAndComments(dateString);
1004             } else if (strncasecmp(dateString, "PM", 2) == 0) {
1005                 if (hour > 12)
1006                     return std::numeric_limits<double>::quiet_NaN();
1007                 if (hour != 12)
1008                     hour += 12;
1009                 dateString += 2;
1010                 skipSpacesAndComments(dateString);
1011             }
1012         }
1013     }
1014     
1015     // The year may be after the time but before the time zone.
1016     if (isASCIIDigit(*dateString) && year == -1) {
1017         if (!parseInt(dateString, &newPosStr, 10, &year))
1018             return std::numeric_limits<double>::quiet_NaN();
1019         dateString = newPosStr;
1020         skipSpacesAndComments(dateString);
1021     }
1022 
1023     // Don't fail if the time zone is missing. 
1024     // Some websites omit the time zone (4275206).
1025     if (*dateString) {
1026         if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
1027             dateString += 3;
1028             haveTZ = true;
1029         }
1030 
1031         if (*dateString == '+' || *dateString == '-') {
1032             int o;
1033             if (!parseInt(dateString, &newPosStr, 10, &o))
1034                 return std::numeric_limits<double>::quiet_NaN();
1035             dateString = newPosStr;
1036 
1037             if (o < -9959 || o > 9959)
1038                 return std::numeric_limits<double>::quiet_NaN();
1039 
1040             int sgn = (o < 0) ? -1 : 1;
1041             o = abs(o);
1042             if (*dateString != ':') {
1043                 if (o >= 24)
1044                     offset = ((o / 100) * 60 + (o % 100)) * sgn;
1045                 else
1046                     offset = o * 60 * sgn;
1047             } else { // GMT+05:00
1048                 ++dateString; // skip the ':'
1049                 int o2;
1050                 if (!parseInt(dateString, &newPosStr, 10, &o2))
1051                     return std::numeric_limits<double>::quiet_NaN();
1052                 dateString = newPosStr;
1053                 offset = (o * 60 + o2) * sgn;
1054             }
1055             haveTZ = true;
1056         } else {
1057             for (size_t i = 0; i < WTF_ARRAY_LENGTH(known_zones); ++i) {
1058                 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
1059                     offset = known_zones[i].tzOffset;
1060                     dateString += strlen(known_zones[i].tzName);
1061                     haveTZ = true;
1062                     break;
1063                 }
1064             }
1065         }
1066     }
1067 
1068     skipSpacesAndComments(dateString);
1069 
1070     if (*dateString && year == -1) {
1071         if (!parseInt(dateString, &newPosStr, 10, &year))
1072             return std::numeric_limits<double>::quiet_NaN();
1073         dateString = newPosStr;
1074         skipSpacesAndComments(dateString);
1075     }
1076 
1077     // Trailing garbage
1078     if (*dateString)
1079         return std::numeric_limits<double>::quiet_NaN();
1080 
1081     // Y2K: Handle 2 digit years.
1082     if (year >= 0 && year < 100) {
1083         if (year < 50)
1084             year += 2000;
1085         else
1086             year += 1900;
1087     }
1088     
1089     return ymdhmsToSeconds(year, month + 1, day, hour, minute, second) * msPerSecond;
1090 }
1091 
1092 double parseDateFromNullTerminatedCharacters(const char* dateString)
1093 {
1094     bool haveTZ;
1095     int offset;
1096     double ms = parseDateFromNullTerminatedCharacters(dateString, haveTZ, offset);
1097     if (std::isnan(ms))
1098         return std::numeric_limits<double>::quiet_NaN();
1099 
1100     // fall back to local timezone
1101     if (!haveTZ)
1102         offset = calculateLocalTimeOffset(ms).offset / msPerMinute;
1103 
1104     return ms - (offset * msPerMinute);
1105 }
1106 
1107 double timeClip(double t)
1108 {
1109     if (!std::isfinite(t))
1110         return std::numeric_limits<double>::quiet_NaN();
1111     if (fabs(t) > maxECMAScriptTime)
1112         return std::numeric_limits<double>::quiet_NaN();
1113     return trunc(t);
1114 }
1115 
1116 // See http://tools.ietf.org/html/rfc2822#section-3.3 for more information.
1117 String makeRFC2822DateString(unsigned dayOfWeek, unsigned day, unsigned month, unsigned year, unsigned hours, unsigned minutes, unsigned seconds, int utcOffset)
1118 {
1119     StringBuilder stringBuilder;
1120     stringBuilder.append(weekdayName[dayOfWeek]);
1121     stringBuilder.appendLiteral(", ");
1122     stringBuilder.appendNumber(day);
1123     stringBuilder.append(' ');
1124     stringBuilder.append(monthName[month]);
1125     stringBuilder.append(' ');
1126     stringBuilder.appendNumber(year);
1127     stringBuilder.append(' ');
1128 
1129     appendTwoDigitNumber(stringBuilder, hours);
1130     stringBuilder.append(':');
1131     appendTwoDigitNumber(stringBuilder, minutes);
1132     stringBuilder.append(':');
1133     appendTwoDigitNumber(stringBuilder, seconds);
1134     stringBuilder.append(' ');
1135 
1136     stringBuilder.append(utcOffset > 0 ? '+' : '-');
1137     int absoluteUTCOffset = abs(utcOffset);
1138     appendTwoDigitNumber(stringBuilder, absoluteUTCOffset / 60);
1139     appendTwoDigitNumber(stringBuilder, absoluteUTCOffset % 60);
1140 
1141     return stringBuilder.toString();
1142 }
1143 
1144 } // namespace WTF