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 105using namespace WTF; 106 107namespace WTF { 108 109/* Constants */ 110 111static 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. 115static 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. 119static 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) 125static 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 137bool 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 148static inline int daysInYear(int year) 149{ 150 return 365 + isLeapYear(year); 151} 152 153static 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 172double msToDays(double ms) 173{ 174 return floor(ms / msPerDay); 175} 176 177static 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 185int 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 196int dayInYear(double ms, int year) 197{ 198 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year)); 199} 200 201static inline double msToMilliseconds(double ms) 202{ 203 double result = fmod(ms, msPerDay); 204 if (result < 0) 205 result += msPerDay; 206 return result; 207} 208 209int 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 217int 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 225int 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 256static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth) 257{ 258 startDayOfThisMonth = startDayOfNextMonth; 259 startDayOfNextMonth += daysInThisMonth; 260 return (dayInYear <= startDayOfNextMonth); 261} 262 263int 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 296int dayInYear(int year, int month, int day) 297{ 298 return firstDayOfMonth[isLeapYear(year)][month] + day - 1; 299} 300 301double 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). 318static inline int maximumYearForDST() 319{ 320 return 2037; 321} 322 323static 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 */ 342int 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 368static 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 411static 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 */ 425static 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 return diff * msPerSecond; 447#else 448 //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset() 449 double offsetTime = (localTime * msPerSecond) + utcOffset; 450 451 // Offset from UTC but doesn't include DST obviously 452 int offsetHour = msToHours(offsetTime); 453 int offsetMinute = msToMinutes(offsetTime); 454 455 tm localTM; 456 getLocalTime(&localTime, &localTM); 457 458 double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60); 459 460 if (diff < 0) 461 diff += secondsPerDay; 462 463 return (diff * msPerSecond); 464#endif 465} 466 467#endif 468 469// Returns combined offset in millisecond (UTC + DST). 470LocalTimeOffset calculateLocalTimeOffset(double ms) 471{ 472 // On Mac OS X, the call to localtime (see calculateDSTOffset) will return historically accurate 473 // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript 474 // standard explicitly dictates that historical information should not be considered when 475 // determining DST. For this reason we shift away from years that localtime can handle but would 476 // return historically accurate information. 477 int year = msToYear(ms); 478 int equivalentYear = equivalentYearForDST(year); 479 if (year != equivalentYear) { 480 bool leapYear = isLeapYear(year); 481 int dayInYearLocal = dayInYear(ms, year); 482 int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear); 483 int month = monthFromDayInYear(dayInYearLocal, leapYear); 484 double day = dateToDaysFrom1970(equivalentYear, month, dayInMonth); 485 ms = (day * msPerDay) + msToMilliseconds(ms); 486 } 487 488 double localTimeSeconds = ms / msPerSecond; 489 if (localTimeSeconds > maxUnixTime) 490 localTimeSeconds = maxUnixTime; 491 else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0). 492 localTimeSeconds += secondsPerDay; 493 // FIXME: time_t has a potential problem in 2038. 494 time_t localTime = static_cast<time_t>(localTimeSeconds); 495 496#if HAVE(TM_GMTOFF) 497 tm localTM; 498 getLocalTime(&localTime, &localTM); 499 return LocalTimeOffset(localTM.tm_isdst, localTM.tm_gmtoff * msPerSecond); 500#else 501 double utcOffset = calculateUTCOffset(); 502 double dstOffset = calculateDSTOffset(localTime, utcOffset); 503 return LocalTimeOffset(dstOffset, utcOffset + dstOffset); 504#endif 505} 506 507void initializeDates() 508{ 509#if !ASSERT_DISABLED 510 static bool alreadyInitialized; 511 ASSERT(!alreadyInitialized); 512 alreadyInitialized = true; 513#endif 514 515 equivalentYearForDST(2000); // Need to call once to initialize a static used in this function. 516} 517 518static inline double ymdhmsToSeconds(int year, long mon, long day, long hour, long minute, double second) 519{ 520 int mday = firstDayOfMonth[isLeapYear(year)][mon - 1]; 521 double ydays = daysFrom1970ToYear(year); 522 523 return (second + minute * secondsPerMinute + hour * secondsPerHour + (mday + day - 1 + ydays) * secondsPerDay); 524} 525 526// We follow the recommendation of RFC 2822 to consider all 527// obsolete time zones not listed here equivalent to "-0000". 528static const struct KnownZone { 529#if !OS(WINDOWS) 530 const 531#endif 532 char tzName[4]; 533 int tzOffset; 534} known_zones[] = { 535 { "UT", 0 }, 536 { "GMT", 0 }, 537 { "EST", -300 }, 538 { "EDT", -240 }, 539 { "CST", -360 }, 540 { "CDT", -300 }, 541 { "MST", -420 }, 542 { "MDT", -360 }, 543 { "PST", -480 }, 544 { "PDT", -420 } 545}; 546 547inline static void skipSpacesAndComments(const char*& s) 548{ 549 int nesting = 0; 550 char ch; 551 while ((ch = *s)) { 552 if (!isASCIISpace(ch)) { 553 if (ch == '(') 554 nesting++; 555 else if (ch == ')' && nesting > 0) 556 nesting--; 557 else if (nesting == 0) 558 break; 559 } 560 s++; 561 } 562} 563 564// returns 0-11 (Jan-Dec); -1 on failure 565static int findMonth(const char* monthStr) 566{ 567 ASSERT(monthStr); 568 char needle[4]; 569 for (int i = 0; i < 3; ++i) { 570 if (!*monthStr) 571 return -1; 572 needle[i] = static_cast<char>(toASCIILower(*monthStr++)); 573 } 574 needle[3] = '\0'; 575 const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec"; 576 const char *str = strstr(haystack, needle); 577 if (str) { 578 int position = static_cast<int>(str - haystack); 579 if (position % 3 == 0) 580 return position / 3; 581 } 582 return -1; 583} 584 585static bool parseInt(const char* string, char** stopPosition, int base, int* result) 586{ 587 long longResult = strtol(string, stopPosition, base); 588 // Avoid the use of errno as it is not available on Windows CE 589 if (string == *stopPosition || longResult <= std::numeric_limits<int>::min() || longResult >= std::numeric_limits<int>::max()) 590 return false; 591 *result = static_cast<int>(longResult); 592 return true; 593} 594 595static bool parseLong(const char* string, char** stopPosition, int base, long* result) 596{ 597 *result = strtol(string, stopPosition, base); 598 // Avoid the use of errno as it is not available on Windows CE 599 if (string == *stopPosition || *result == std::numeric_limits<long>::min() || *result == std::numeric_limits<long>::max()) 600 return false; 601 return true; 602} 603 604// Parses a date with the format YYYY[-MM[-DD]]. 605// Year parsing is lenient, allows any number of digits, and +/-. 606// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string. 607static char* parseES5DatePortion(const char* currentPosition, int& year, long& month, long& day) 608{ 609 char* postParsePosition; 610 611 // This is a bit more lenient on the year string than ES5 specifies: 612 // instead of restricting to 4 digits (or 6 digits with mandatory +/-), 613 // it accepts any integer value. Consider this an implementation fallback. 614 if (!parseInt(currentPosition, &postParsePosition, 10, &year)) 615 return 0; 616 617 // Check for presence of -MM portion. 618 if (*postParsePosition != '-') 619 return postParsePosition; 620 currentPosition = postParsePosition + 1; 621 622 if (!isASCIIDigit(*currentPosition)) 623 return 0; 624 if (!parseLong(currentPosition, &postParsePosition, 10, &month)) 625 return 0; 626 if ((postParsePosition - currentPosition) != 2) 627 return 0; 628 629 // Check for presence of -DD portion. 630 if (*postParsePosition != '-') 631 return postParsePosition; 632 currentPosition = postParsePosition + 1; 633 634 if (!isASCIIDigit(*currentPosition)) 635 return 0; 636 if (!parseLong(currentPosition, &postParsePosition, 10, &day)) 637 return 0; 638 if ((postParsePosition - currentPosition) != 2) 639 return 0; 640 return postParsePosition; 641} 642 643// Parses a time with the format HH:mm[:ss[.sss]][Z|(+|-)00:00]. 644// Fractional seconds parsing is lenient, allows any number of digits. 645// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string. 646static char* parseES5TimePortion(char* currentPosition, long& hours, long& minutes, double& seconds, long& timeZoneSeconds) 647{ 648 char* postParsePosition; 649 if (!isASCIIDigit(*currentPosition)) 650 return 0; 651 if (!parseLong(currentPosition, &postParsePosition, 10, &hours)) 652 return 0; 653 if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2) 654 return 0; 655 currentPosition = postParsePosition + 1; 656 657 if (!isASCIIDigit(*currentPosition)) 658 return 0; 659 if (!parseLong(currentPosition, &postParsePosition, 10, &minutes)) 660 return 0; 661 if ((postParsePosition - currentPosition) != 2) 662 return 0; 663 currentPosition = postParsePosition; 664 665 // Seconds are optional. 666 if (*currentPosition == ':') { 667 ++currentPosition; 668 669 long intSeconds; 670 if (!isASCIIDigit(*currentPosition)) 671 return 0; 672 if (!parseLong(currentPosition, &postParsePosition, 10, &intSeconds)) 673 return 0; 674 if ((postParsePosition - currentPosition) != 2) 675 return 0; 676 seconds = intSeconds; 677 if (*postParsePosition == '.') { 678 currentPosition = postParsePosition + 1; 679 680 // In ECMA-262-5 it's a bit unclear if '.' can be present without milliseconds, but 681 // a reasonable interpretation guided by the given examples and RFC 3339 says "no". 682 // We check the next character to avoid reading +/- timezone hours after an invalid decimal. 683 if (!isASCIIDigit(*currentPosition)) 684 return 0; 685 686 // We are more lenient than ES5 by accepting more or less than 3 fraction digits. 687 long fracSeconds; 688 if (!parseLong(currentPosition, &postParsePosition, 10, &fracSeconds)) 689 return 0; 690 691 long numFracDigits = postParsePosition - currentPosition; 692 seconds += fracSeconds * pow(10.0, static_cast<double>(-numFracDigits)); 693 } 694 currentPosition = postParsePosition; 695 } 696 697 if (*currentPosition == 'Z') 698 return currentPosition + 1; 699 700 bool tzNegative; 701 if (*currentPosition == '-') 702 tzNegative = true; 703 else if (*currentPosition == '+') 704 tzNegative = false; 705 else 706 return currentPosition; // no timezone 707 ++currentPosition; 708 709 long tzHours; 710 long tzHoursAbs; 711 long tzMinutes; 712 713 if (!isASCIIDigit(*currentPosition)) 714 return 0; 715 if (!parseLong(currentPosition, &postParsePosition, 10, &tzHours)) 716 return 0; 717 if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2) 718 return 0; 719 tzHoursAbs = labs(tzHours); 720 currentPosition = postParsePosition + 1; 721 722 if (!isASCIIDigit(*currentPosition)) 723 return 0; 724 if (!parseLong(currentPosition, &postParsePosition, 10, &tzMinutes)) 725 return 0; 726 if ((postParsePosition - currentPosition) != 2) 727 return 0; 728 currentPosition = postParsePosition; 729 730 if (tzHoursAbs > 24) 731 return 0; 732 if (tzMinutes < 0 || tzMinutes > 59) 733 return 0; 734 735 timeZoneSeconds = 60 * (tzMinutes + (60 * tzHoursAbs)); 736 if (tzNegative) 737 timeZoneSeconds = -timeZoneSeconds; 738 739 return currentPosition; 740} 741 742double parseES5DateFromNullTerminatedCharacters(const char* dateString) 743{ 744 // This parses a date of the form defined in ECMA-262-5, section 15.9.1.15 745 // (similar to RFC 3339 / ISO 8601: YYYY-MM-DDTHH:mm:ss[.sss]Z). 746 // In most cases it is intentionally strict (e.g. correct field widths, no stray whitespace). 747 748 static const long daysPerMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 749 750 // The year must be present, but the other fields may be omitted - see ES5.1 15.9.1.15. 751 int year = 0; 752 long month = 1; 753 long day = 1; 754 long hours = 0; 755 long minutes = 0; 756 double seconds = 0; 757 long timeZoneSeconds = 0; 758 759 // Parse the date YYYY[-MM[-DD]] 760 char* currentPosition = parseES5DatePortion(dateString, year, month, day); 761 if (!currentPosition) 762 return std::numeric_limits<double>::quiet_NaN(); 763 // Look for a time portion. 764 if (*currentPosition == 'T') { 765 // Parse the time HH:mm[:ss[.sss]][Z|(+|-)00:00] 766 currentPosition = parseES5TimePortion(currentPosition + 1, hours, minutes, seconds, timeZoneSeconds); 767 if (!currentPosition) 768 return std::numeric_limits<double>::quiet_NaN(); 769 } 770 // Check that we have parsed all characters in the string. 771 if (*currentPosition) 772 return std::numeric_limits<double>::quiet_NaN(); 773 774 // A few of these checks could be done inline above, but since many of them are interrelated 775 // we would be sacrificing readability to "optimize" the (presumably less common) failure path. 776 if (month < 1 || month > 12) 777 return std::numeric_limits<double>::quiet_NaN(); 778 if (day < 1 || day > daysPerMonth[month - 1]) 779 return std::numeric_limits<double>::quiet_NaN(); 780 if (month == 2 && day > 28 && !isLeapYear(year)) 781 return std::numeric_limits<double>::quiet_NaN(); 782 if (hours < 0 || hours > 24) 783 return std::numeric_limits<double>::quiet_NaN(); 784 if (hours == 24 && (minutes || seconds)) 785 return std::numeric_limits<double>::quiet_NaN(); 786 if (minutes < 0 || minutes > 59) 787 return std::numeric_limits<double>::quiet_NaN(); 788 if (seconds < 0 || seconds >= 61) 789 return std::numeric_limits<double>::quiet_NaN(); 790 if (seconds > 60) { 791 // Discard leap seconds by clamping to the end of a minute. 792 seconds = 60; 793 } 794 795 double dateSeconds = ymdhmsToSeconds(year, month, day, hours, minutes, seconds) - timeZoneSeconds; 796 return dateSeconds * msPerSecond; 797} 798 799// Odd case where 'exec' is allowed to be 0, to accomodate a caller in WebCore. 800double parseDateFromNullTerminatedCharacters(const char* dateString, bool& haveTZ, int& offset) 801{ 802 haveTZ = false; 803 offset = 0; 804 805 // This parses a date in the form: 806 // Tuesday, 09-Nov-99 23:12:40 GMT 807 // or 808 // Sat, 01-Jan-2000 08:00:00 GMT 809 // or 810 // Sat, 01 Jan 2000 08:00:00 GMT 811 // or 812 // 01 Jan 99 22:00 +0100 (exceptions in rfc822/rfc2822) 813 // ### non RFC formats, added for Javascript: 814 // [Wednesday] January 09 1999 23:12:40 GMT 815 // [Wednesday] January 09 23:12:40 GMT 1999 816 // 817 // We ignore the weekday. 818 819 // Skip leading space 820 skipSpacesAndComments(dateString); 821 822 long month = -1; 823 const char *wordStart = dateString; 824 // Check contents of first words if not number 825 while (*dateString && !isASCIIDigit(*dateString)) { 826 if (isASCIISpace(*dateString) || *dateString == '(') { 827 if (dateString - wordStart >= 3) 828 month = findMonth(wordStart); 829 skipSpacesAndComments(dateString); 830 wordStart = dateString; 831 } else 832 dateString++; 833 } 834 835 // Missing delimiter between month and day (like "January29")? 836 if (month == -1 && wordStart != dateString) 837 month = findMonth(wordStart); 838 839 skipSpacesAndComments(dateString); 840 841 if (!*dateString) 842 return std::numeric_limits<double>::quiet_NaN(); 843 844 // ' 09-Nov-99 23:12:40 GMT' 845 char* newPosStr; 846 long day; 847 if (!parseLong(dateString, &newPosStr, 10, &day)) 848 return std::numeric_limits<double>::quiet_NaN(); 849 dateString = newPosStr; 850 851 if (!*dateString) 852 return std::numeric_limits<double>::quiet_NaN(); 853 854 if (day < 0) 855 return std::numeric_limits<double>::quiet_NaN(); 856 857 int year = 0; 858 if (day > 31) { 859 // ### where is the boundary and what happens below? 860 if (*dateString != '/') 861 return std::numeric_limits<double>::quiet_NaN(); 862 // looks like a YYYY/MM/DD date 863 if (!*++dateString) 864 return std::numeric_limits<double>::quiet_NaN(); 865 if (day <= std::numeric_limits<int>::min() || day >= std::numeric_limits<int>::max()) 866 return std::numeric_limits<double>::quiet_NaN(); 867 year = static_cast<int>(day); 868 if (!parseLong(dateString, &newPosStr, 10, &month)) 869 return std::numeric_limits<double>::quiet_NaN(); 870 month -= 1; 871 dateString = newPosStr; 872 if (*dateString++ != '/' || !*dateString) 873 return std::numeric_limits<double>::quiet_NaN(); 874 if (!parseLong(dateString, &newPosStr, 10, &day)) 875 return std::numeric_limits<double>::quiet_NaN(); 876 dateString = newPosStr; 877 } else if (*dateString == '/' && month == -1) { 878 dateString++; 879 // This looks like a MM/DD/YYYY date, not an RFC date. 880 month = day - 1; // 0-based 881 if (!parseLong(dateString, &newPosStr, 10, &day)) 882 return std::numeric_limits<double>::quiet_NaN(); 883 if (day < 1 || day > 31) 884 return std::numeric_limits<double>::quiet_NaN(); 885 dateString = newPosStr; 886 if (*dateString == '/') 887 dateString++; 888 if (!*dateString) 889 return std::numeric_limits<double>::quiet_NaN(); 890 } else { 891 if (*dateString == '-') 892 dateString++; 893 894 skipSpacesAndComments(dateString); 895 896 if (*dateString == ',') 897 dateString++; 898 899 if (month == -1) { // not found yet 900 month = findMonth(dateString); 901 if (month == -1) 902 return std::numeric_limits<double>::quiet_NaN(); 903 904 while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString)) 905 dateString++; 906 907 if (!*dateString) 908 return std::numeric_limits<double>::quiet_NaN(); 909 910 // '-99 23:12:40 GMT' 911 if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString)) 912 return std::numeric_limits<double>::quiet_NaN(); 913 dateString++; 914 } 915 } 916 917 if (month < 0 || month > 11) 918 return std::numeric_limits<double>::quiet_NaN(); 919 920 // '99 23:12:40 GMT' 921 if (year <= 0 && *dateString) { 922 if (!parseInt(dateString, &newPosStr, 10, &year)) 923 return std::numeric_limits<double>::quiet_NaN(); 924 } 925 926 // Don't fail if the time is missing. 927 long hour = 0; 928 long minute = 0; 929 long second = 0; 930 if (!*newPosStr) 931 dateString = newPosStr; 932 else { 933 // ' 23:12:40 GMT' 934 if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) { 935 if (*newPosStr != ':') 936 return std::numeric_limits<double>::quiet_NaN(); 937 // There was no year; the number was the hour. 938 year = -1; 939 } else { 940 // in the normal case (we parsed the year), advance to the next number 941 dateString = ++newPosStr; 942 skipSpacesAndComments(dateString); 943 } 944 945 parseLong(dateString, &newPosStr, 10, &hour); 946 // Do not check for errno here since we want to continue 947 // even if errno was set becasue we are still looking 948 // for the timezone! 949 950 // Read a number? If not, this might be a timezone name. 951 if (newPosStr != dateString) { 952 dateString = newPosStr; 953 954 if (hour < 0 || hour > 23) 955 return std::numeric_limits<double>::quiet_NaN(); 956 957 if (!*dateString) 958 return std::numeric_limits<double>::quiet_NaN(); 959 960 // ':12:40 GMT' 961 if (*dateString++ != ':') 962 return std::numeric_limits<double>::quiet_NaN(); 963 964 if (!parseLong(dateString, &newPosStr, 10, &minute)) 965 return std::numeric_limits<double>::quiet_NaN(); 966 dateString = newPosStr; 967 968 if (minute < 0 || minute > 59) 969 return std::numeric_limits<double>::quiet_NaN(); 970 971 // ':40 GMT' 972 if (*dateString && *dateString != ':' && !isASCIISpace(*dateString)) 973 return std::numeric_limits<double>::quiet_NaN(); 974 975 // seconds are optional in rfc822 + rfc2822 976 if (*dateString ==':') { 977 dateString++; 978 979 if (!parseLong(dateString, &newPosStr, 10, &second)) 980 return std::numeric_limits<double>::quiet_NaN(); 981 dateString = newPosStr; 982 983 if (second < 0 || second > 59) 984 return std::numeric_limits<double>::quiet_NaN(); 985 } 986 987 skipSpacesAndComments(dateString); 988 989 if (strncasecmp(dateString, "AM", 2) == 0) { 990 if (hour > 12) 991 return std::numeric_limits<double>::quiet_NaN(); 992 if (hour == 12) 993 hour = 0; 994 dateString += 2; 995 skipSpacesAndComments(dateString); 996 } else if (strncasecmp(dateString, "PM", 2) == 0) { 997 if (hour > 12) 998 return std::numeric_limits<double>::quiet_NaN(); 999 if (hour != 12) 1000 hour += 12; 1001 dateString += 2; 1002 skipSpacesAndComments(dateString); 1003 } 1004 } 1005 } 1006 1007 // The year may be after the time but before the time zone. 1008 if (isASCIIDigit(*dateString) && year == -1) { 1009 if (!parseInt(dateString, &newPosStr, 10, &year)) 1010 return std::numeric_limits<double>::quiet_NaN(); 1011 dateString = newPosStr; 1012 skipSpacesAndComments(dateString); 1013 } 1014 1015 // Don't fail if the time zone is missing. 1016 // Some websites omit the time zone (4275206). 1017 if (*dateString) { 1018 if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) { 1019 dateString += 3; 1020 haveTZ = true; 1021 } 1022 1023 if (*dateString == '+' || *dateString == '-') { 1024 int o; 1025 if (!parseInt(dateString, &newPosStr, 10, &o)) 1026 return std::numeric_limits<double>::quiet_NaN(); 1027 dateString = newPosStr; 1028 1029 if (o < -9959 || o > 9959) 1030 return std::numeric_limits<double>::quiet_NaN(); 1031 1032 int sgn = (o < 0) ? -1 : 1; 1033 o = abs(o); 1034 if (*dateString != ':') { 1035 if (o >= 24) 1036 offset = ((o / 100) * 60 + (o % 100)) * sgn; 1037 else 1038 offset = o * 60 * sgn; 1039 } else { // GMT+05:00 1040 ++dateString; // skip the ':' 1041 int o2; 1042 if (!parseInt(dateString, &newPosStr, 10, &o2)) 1043 return std::numeric_limits<double>::quiet_NaN(); 1044 dateString = newPosStr; 1045 offset = (o * 60 + o2) * sgn; 1046 } 1047 haveTZ = true; 1048 } else { 1049 for (size_t i = 0; i < WTF_ARRAY_LENGTH(known_zones); ++i) { 1050 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) { 1051 offset = known_zones[i].tzOffset; 1052 dateString += strlen(known_zones[i].tzName); 1053 haveTZ = true; 1054 break; 1055 } 1056 } 1057 } 1058 } 1059 1060 skipSpacesAndComments(dateString); 1061 1062 if (*dateString && year == -1) { 1063 if (!parseInt(dateString, &newPosStr, 10, &year)) 1064 return std::numeric_limits<double>::quiet_NaN(); 1065 dateString = newPosStr; 1066 skipSpacesAndComments(dateString); 1067 } 1068 1069 // Trailing garbage 1070 if (*dateString) 1071 return std::numeric_limits<double>::quiet_NaN(); 1072 1073 // Y2K: Handle 2 digit years. 1074 if (year >= 0 && year < 100) { 1075 if (year < 50) 1076 year += 2000; 1077 else 1078 year += 1900; 1079 } 1080 1081 return ymdhmsToSeconds(year, month + 1, day, hour, minute, second) * msPerSecond; 1082} 1083 1084double parseDateFromNullTerminatedCharacters(const char* dateString) 1085{ 1086 bool haveTZ; 1087 int offset; 1088 double ms = parseDateFromNullTerminatedCharacters(dateString, haveTZ, offset); 1089 if (std::isnan(ms)) 1090 return std::numeric_limits<double>::quiet_NaN(); 1091 1092 // fall back to local timezone 1093 if (!haveTZ) 1094 offset = calculateLocalTimeOffset(ms).offset / msPerMinute; 1095 1096 return ms - (offset * msPerMinute); 1097} 1098 1099double timeClip(double t) 1100{ 1101 if (!std::isfinite(t)) 1102 return std::numeric_limits<double>::quiet_NaN(); 1103 if (fabs(t) > maxECMAScriptTime) 1104 return std::numeric_limits<double>::quiet_NaN(); 1105 return trunc(t); 1106} 1107 1108// See http://tools.ietf.org/html/rfc2822#section-3.3 for more information. 1109String makeRFC2822DateString(unsigned dayOfWeek, unsigned day, unsigned month, unsigned year, unsigned hours, unsigned minutes, unsigned seconds, int utcOffset) 1110{ 1111 StringBuilder stringBuilder; 1112 stringBuilder.append(weekdayName[dayOfWeek]); 1113 stringBuilder.appendLiteral(", "); 1114 stringBuilder.appendNumber(day); 1115 stringBuilder.append(' '); 1116 stringBuilder.append(monthName[month]); 1117 stringBuilder.append(' '); 1118 stringBuilder.appendNumber(year); 1119 stringBuilder.append(' '); 1120 1121 appendTwoDigitNumber(stringBuilder, hours); 1122 stringBuilder.append(':'); 1123 appendTwoDigitNumber(stringBuilder, minutes); 1124 stringBuilder.append(':'); 1125 appendTwoDigitNumber(stringBuilder, seconds); 1126 stringBuilder.append(' '); 1127 1128 stringBuilder.append(utcOffset > 0 ? '+' : '-'); 1129 int absoluteUTCOffset = abs(utcOffset); 1130 appendTwoDigitNumber(stringBuilder, absoluteUTCOffset / 60); 1131 appendTwoDigitNumber(stringBuilder, absoluteUTCOffset % 60); 1132 1133 return stringBuilder.toString(); 1134} 1135 1136} // namespace WTF 1137