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