Untitled diff

Created Diff never expires
108 removals
Lines
Total
Removed
Words
Total
Removed
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
752 lines
111 additions
Lines
Total
Added
Words
Total
Added
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
756 lines
/*
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
* Copyright (C) 2007-2009 Torch Mobile, Inc.
* Copyright (C) 2007-2009 Torch Mobile, Inc.
* Copyright (C) 2010 &yet, LLC. (nate@andyet.net)
* Copyright (C) 2010 &yet, LLC. (nate@andyet.net)
*
*
* The Original Code is Mozilla Communicator client code, released
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
* March 31, 1998.
*
*
* The Initial Developer of the Original Code is
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
* the Initial Developer. All Rights Reserved.
*
*
* This library is free software; you can redistribute it and/or
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* version 2.1 of the License, or (at your option) any later version.
*
*
* This library is distributed in the hope that it will be useful,
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* Lesser General Public License for more details.
*
*
* You should have received a copy of the GNU Lesser General Public
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*
* Alternatively, the contents of this file may be used under the terms
* Alternatively, the contents of this file may be used under the terms
* of either the Mozilla Public License Version 1.1, found at
* of either the Mozilla Public License Version 1.1, found at
* http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
* http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
* License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
* License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
* (the "GPL"), in which case the provisions of the MPL or the GPL are
* (the "GPL"), in which case the provisions of the MPL or the GPL are
* applicable instead of those above. If you wish to allow use of your
* applicable instead of those above. If you wish to allow use of your
* version of this file only under the terms of one of those two
* version of this file only under the terms of one of those two
* licenses (the MPL or the GPL) and not to allow others to use your
* licenses (the MPL or the GPL) and not to allow others to use your
* version of this file under the LGPL, indicate your decision by
* version of this file under the LGPL, indicate your decision by
* deletingthe provisions above and replace them with the notice and
* deletingthe provisions above and replace them with the notice and
* other provisions required by the MPL or the GPL, as the case may be.
* other provisions required by the MPL or the GPL, as the case may be.
* If you do not delete the provisions above, a recipient may use your
* If you do not delete the provisions above, a recipient may use your
* version of this file under any of the LGPL, the MPL or the GPL.
* version of this file under any of the LGPL, the MPL or the GPL.


* Copyright 2006-2008 the V8 project authors. All rights reserved.
* Copyright 2006-2008 the V8 project authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
* met:
*
*
* * Redistributions of source code must retain the above copyright
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
*/


#include "config.h"
#include "config.h"
#include "DateMath.h"
#include "DateMath.h"


#include "Assertions.h"
#include "Assertions.h"
#include "ASCIICType.h"
#include "ASCIICType.h"
#include "CurrentTime.h"
#include "CurrentTime.h"
#include "MathExtras.h"
#include "MathExtras.h"
#include "StdLibExtras.h"
#include "StdLibExtras.h"
#include "StringExtras.h"
#include "StringExtras.h"


#include <algorithm>
#include <algorithm>
#include <limits.h>
#include <limits.h>
#include <limits>
#include <limits>
#include <stdint.h>
#include <stdint.h>
#include <time.h>
#include <time.h>
#include <wtf/Optional.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringBuilder.h>


#if OS(WINDOWS)
#if OS(WINDOWS)
#include <windows.h>
#include <windows.h>
#endif
#endif


#if HAVE(ERRNO_H)
#if HAVE(ERRNO_H)
#include <errno.h>
#include <errno.h>
#endif
#endif


#if HAVE(SYS_TIME_H)
#if HAVE(SYS_TIME_H)
#include <sys/time.h>
#include <sys/time.h>
#endif
#endif


#if HAVE(SYS_TIMEB_H)
#if HAVE(SYS_TIMEB_H)
#include <sys/timeb.h>
#include <sys/timeb.h>
#endif
#endif


#if OS(QNX)
// qnx6 defines timegm in nbutil.h
#include <nbutil.h>
#endif

using namespace WTF;
using namespace WTF;


namespace WTF {
namespace WTF {


/* Constants */
/* Constants */


static const double minutesPerDay = 24.0 * 60.0;
static const double secondsPerDay = 24.0 * 60.0 * 60.0;
static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;

static const double usecPerSec = 1000000.0;

static const double maxUnixTime = 2145859200.0; // 12/31/2037
static const double maxUnixTime = 2145859200.0; // 12/31/2037
// ECMAScript asks not to support for a date of which total
// ECMAScript asks not to support for a date of which total
// millisecond value is larger than the following value.
// millisecond value is larger than the following value.
// See 15.9.1.14 of ECMA-262 5th edition.
// See 15.9.1.14 of ECMA-262 5th edition.
static const double maxECMAScriptTime = 8.64E15;
static const double maxECMAScriptTime = 8.64E15;


// Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
// Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
// First for non-leap years, then for leap years.
// First for non-leap years, then for leap years.
static const int firstDayOfMonth[2][12] = {
static const int firstDayOfMonth[2][12] = {
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
};
};


#if !OS(WINCE)
static inline void getLocalTime(const time_t* localTime, struct tm* localTM)
static inline void getLocalTime(const time_t* localTime, struct tm* localTM)
{
{
#if COMPILER(MINGW)
#if COMPILER(MINGW)
*localTM = *localtime(localTime);
*localTM = *localtime(localTime);
#elif COMPILER(MSVC)
#elif COMPILER(MSVC)
localtime_s(localTM, localTime);
localtime_s(localTM, localTime);
#else
#else
localtime_r(localTime, localTM);
localtime_r(localTime, localTM);
#endif
#endif
}
}
#endif


bool isLeapYear(int year)
bool isLeapYear(int year)
{
{
if (year % 4 != 0)
if (year % 4 != 0)
return false;
return false;
if (year % 400 == 0)
if (year % 400 == 0)
return true;
return true;
if (year % 100 == 0)
if (year % 100 == 0)
return false;
return false;
return true;
return true;
}
}


static inline int daysInYear(int year)
static inline int daysInYear(int year)
{
{
return 365 + isLeapYear(year);
return 365 + isLeapYear(year);
}
}


static inline double daysFrom1970ToYear(int year)
static inline double daysFrom1970ToYear(int year)
{
{
// The Gregorian Calendar rules for leap years:
// The Gregorian Calendar rules for leap years:
// Every fourth year is a leap year. 2004, 2008, and 2012 are leap years.
// Every fourth year is a leap year. 2004, 2008, and 2012 are leap years.
// However, every hundredth year is not a leap year. 1900 and 2100 are not leap years.
// However, every hundredth year is not a leap year. 1900 and 2100 are not leap years.
// Every four hundred years, there's a leap year after all. 2000 and 2400 are leap years.
// Every four hundred years, there's a leap year after all. 2000 and 2400 are leap years.


static const int leapDaysBefore1971By4Rule = 1970 / 4;
static const int leapDaysBefore1971By4Rule = 1970 / 4;
static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
static const int leapDaysBefore1971By400Rule = 1970 / 400;
static const int leapDaysBefore1971By400Rule = 1970 / 400;


const double yearMinusOne = year - 1;
const double yearMinusOne = year - 1;
const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;


return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
}
}


double msToDays(double ms)
double msToDays(double ms)
{
{
return floor(ms / msPerDay);
return floor(ms / msPerDay);
}
}


static void appendTwoDigitNumber(StringBuilder& builder, int number)
static String twoDigitStringFromNumber(int number)
{
{
ASSERT(number >= 0);
ASSERT(number >= 0 && number < 100);
ASSERT(number < 100);
if (number > 9)
builder.append(static_cast<LChar>('0' + number / 10));
return String::number(number);
builder.append(static_cast<LChar>('0' + number % 10));
return makeString("0", String::number(number));
}
}


int msToYear(double ms)
int msToYear(double ms)
{
{
int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
if (msFromApproxYearTo1970 > ms)
if (msFromApproxYearTo1970 > ms)
return approxYear - 1;
return approxYear - 1;
if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
return approxYear + 1;
return approxYear + 1;
return approxYear;
return approxYear;
}
}


int dayInYear(double ms, int year)
int dayInYear(double ms, int year)
{
{
return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
}
}


static inline double msToMilliseconds(double ms)
static inline double msToMilliseconds(double ms)
{
{
double result = fmod(ms, msPerDay);
double result = fmod(ms, msPerDay);
if (result < 0)
if (result < 0)
result += msPerDay;
result += msPerDay;
return result;
return result;
}
}


int msToMinutes(double ms)
int msToMinutes(double ms)
{
{
double result = fmod(floor(ms / msPerMinute), minutesPerHour);
double result = fmod(floor(ms / msPerMinute), minutesPerHour);
if (result < 0)
if (result < 0)
result += minutesPerHour;
result += minutesPerHour;
return static_cast<int>(result);
return static_cast<int>(result);
}
}


int msToHours(double ms)
int msToHours(double ms)
{
{
double result = fmod(floor(ms/msPerHour), hoursPerDay);
double result = fmod(floor(ms/msPerHour), hoursPerDay);
if (result < 0)
if (result < 0)
result += hoursPerDay;
result += hoursPerDay;
return static_cast<int>(result);
return static_cast<int>(result);
}
}


int monthFromDayInYear(int dayInYear, bool leapYear)
int monthFromDayInYear(int dayInYear, bool leapYear)
{
{
const int d = dayInYear;
const int d = dayInYear;
int step;
int step;


if (d < (step = 31))
if (d < (step = 31))
return 0;
return 0;
step += (leapYear ? 29 : 28);
step += (leapYear ? 29 : 28);
if (d < step)
if (d < step)
return 1;
return 1;
if (d < (step += 31))
if (d < (step += 31))
return 2;
return 2;
if (d < (step += 30))
if (d < (step += 30))
return 3;
return 3;
if (d < (step += 31))
if (d < (step += 31))
return 4;
return 4;
if (d < (step += 30))
if (d < (step += 30))
return 5;
return 5;
if (d < (step += 31))
if (d < (step += 31))
return 6;
return 6;
if (d < (step += 31))
if (d < (step += 31))
return 7;
return 7;
if (d < (step += 30))
if (d < (step += 30))
return 8;
return 8;
if (d < (step += 31))
if (d < (step += 31))
return 9;
return 9;
if (d < (step += 30))
if (d < (step += 30))
return 10;
return 10;
return 11;
return 11;
}
}


static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
{
{
startDayOfThisMonth = startDayOfNextMonth;
startDayOfThisMonth = startDayOfNextMonth;
startDayOfNextMonth += daysInThisMonth;
startDayOfNextMonth += daysInThisMonth;
return (dayInYear <= startDayOfNextMonth);
return (dayInYear <= startDayOfNextMonth);
}
}


int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
{
{
const int d = dayInYear;
const int d = dayInYear;
int step;
int step;
int next = 30;
int next = 30;


if (d <= next)
if (d <= next)
return d + 1;
return d + 1;
const int daysInFeb = (leapYear ? 29 : 28);
const int daysInFeb = (leapYear ? 29 : 28);
if (checkMonth(d, step, next, daysInFeb))
if (checkMonth(d, step, next, daysInFeb))
return d - step;
return d - step;
if (checkMonth(d, step, next, 31))
if (checkMonth(d, step, next, 31))
return d - step;
return d - step;
if (checkMonth(d, step, next, 30))
if (checkMonth(d, step, next, 30))
return d - step;
return d - step;
if (checkMonth(d, step, next, 31))
if (checkMonth(d, step, next, 31))
return d - step;
return d - step;
if (checkMonth(d, step, next, 30))
if (checkMonth(d, step, next, 30))
return d - step;
return d - step;
if (checkMonth(d, step, next, 31))
if (checkMonth(d, step, next, 31))
return d - step;
return d - step;
if (checkMonth(d, step, next, 31))
if (checkMonth(d, step, next, 31))
return d - step;
return d - step;
if (checkMonth(d, step, next, 30))
if (checkMonth(d, step, next, 30))
return d - step;
return d - step;
if (checkMonth(d, step, next, 31))
if (checkMonth(d, step, next, 31))
return d - step;
return d - step;
if (checkMonth(d, step, next, 30))
if (checkMonth(d, step, next, 30))
return d - step;
return d - step;
step = next;
step = next;
return d - step;
return d - step;
}
}


int dayInYear(int year, int month, int day)
int dayInYear(int year, int month, int day)
{
{
return firstDayOfMonth[isLeapYear(year)][month] + day - 1;
return firstDayOfMonth[isLeapYear(year)][month] + day - 1;
}
}


double dateToDaysFrom1970(int year, int month, int day)
double dateToDaysFrom1970(int year, int month, int day)
{
{
year += month / 12;
year += month / 12;


month %= 12;
month %= 12;
if (month < 0) {
if (month < 0) {
month += 12;
month += 12;
--year;
--year;
}
}


double yearday = floor(daysFrom1970ToYear(year));
double yearday = floor(daysFrom1970ToYear(year));
ASSERT((year >= 1970 && yearday >= 0) || (year < 1970 && yearday < 0));
ASSERT((year >= 1970 && yearday >= 0) || (year < 1970 && yearday < 0));
return yearday + dayInYear(year, month, day);
return yearday + dayInYear(year, month, day);
}
}


// There is a hard limit at 2038 that we currently do not have a workaround
// There is a hard limit at 2038 that we currently do not have a workaround
// for (rdar://problem/5052975).
// for (rdar://problem/5052975).
static inline int maximumYearForDST()
static inline int maximumYearForDST()
{
{
return 2037;
return 2037;
}
}


static inline int minimumYearForDST()
static inline int minimumYearForDST()
{
{
// Because of the 2038 issue (see maximumYearForDST) if the current year is
// Because of the 2038 issue (see maximumYearForDST) if the current year is
// greater than the max year minus 27 (2010), we want to use the max year
// greater than the max year minus 27 (2010), we want to use the max year
// minus 27 instead, to ensure there is a range of 28 years that all years
// minus 27 instead, to ensure there is a range of 28 years that all years
// can map to.
// can map to.
return std::min(msToYear(jsCurrentTime()), maximumYearForDST() - 27) ;
return std::min(msToYear(jsCurrentTime()), maximumYearForDST() - 27) ;
}
}


/*
/*
* Find an equivalent year for the one given, where equivalence is deterined by
* Find an equivalent year for the one given, where equivalence is deterined by
* the two years having the same leapness and the first day of the year, falling
* the two years having the same leapness and the first day of the year, falling
* on the same day of the week.
* on the same day of the week.
*
*
* This function returns a year between this current year and 2037, however this
* This function returns a year between this current year and 2037, however this
* function will potentially return incorrect results if the current year is after
* function will potentially return incorrect results if the current year is after
* 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
* 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
* 2100, (rdar://problem/5055038).
* 2100, (rdar://problem/5055038).
*/
*/
int equivalentYearForDST(int year)
int equivalentYearForDST(int year)
{
{
// It is ok if the cached year is not the current year as long as the rules
// It is ok if the cached year is not the current year as long as the rules
// for DST did not change between the two years; if they did the app would need
// for DST did not change between the two years; if they did the app would need
// to be restarted.
// to be restarted.
static int minYear = minimumYearForDST();
static int minYear = minimumYearForDST();
int maxYear = maximumYearForDST();
int maxYear = maximumYearForDST();


int difference;
int difference;
if (year > maxYear)
if (year > maxYear)
difference = minYear - year;
difference = minYear - year;
else if (year < minYear)
else if (year < minYear)
difference = maxYear - year;
difference = maxYear - year;
else
else
return year;
return year;


int quotient = difference / 28;
int quotient = difference / 28;
int product = (quotient) * 28;
int product = (quotient) * 28;


year += product;
year += product;
ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(std::numeric_limits<double>::quiet_NaN())));
ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(std::numeric_limits<double>::quiet_NaN())));
return year;
return year;
}
}


#if OS(WINDOWS)
#if !HAVE(TM_GMTOFF)
typedef BOOL(WINAPI* callGetTimeZoneInformationForYear_t)(USHORT, PDYNAMIC_TIME_ZONE_INFORMATION, LPTIME_ZONE_INFORMATION);

static callGetTimeZoneInformationForYear_t timeZoneInformationForYearFunction()
{
static callGetTimeZoneInformationForYear_t getTimeZoneInformationForYear = nullptr;

if (getTimeZoneInformationForYear)
return getTimeZoneInformationForYear;

HMODULE module = ::GetModuleHandleW(L"kernel32.dll");
if (!module)
return nullptr;

getTimeZoneInformationForYear = reinterpret_cast<callGetTimeZoneInformationForYear_t>(::GetProcAddress(module, "GetTimeZoneInformationForYear"));

return getTimeZoneInformationForYear;
}
#endif


static int32_t calculateUTCOffset()
static int32_t calculateUTCOffset()
{
{
#if OS(WINDOWS)
#if OS(WINDOWS)
TIME_ZONE_INFORMATION timeZoneInformation;
TIME_ZONE_INFORMATION timeZoneInformation;
DWORD rc = 0;
GetTimeZoneInformation(&timeZoneInformation);

int32_t bias = timeZoneInformation.Bias + timeZoneInformation.StandardBias;
if (callGetTimeZoneInformationForYear_t timeZoneFunction = timeZoneInformationForYearFunction()) {
// If available, use the Windows API call that takes into account the varying DST from
// year to year.
SYSTEMTIME systemTime;
::GetSystemTime(&systemTime);
rc = timeZoneFunction(systemTime.wYear, nullptr, &timeZoneInformation);
if (rc == TIME_ZONE_ID_INVALID)
return 0;
} else {
rc = ::GetTimeZoneInformation(&timeZoneInformation);
if (rc == TIME_ZONE_ID_INVALID)
return 0;
}

int32_t bias = timeZoneInformation.Bias;

if (rc == TIME_ZONE_ID_DAYLIGHT)
bias += timeZoneInformation.DaylightBias;
else if (rc == TIME_ZONE_ID_STANDARD || rc == TIME_ZONE_ID_UNKNOWN)
bias += timeZoneInformation.StandardBias;

return -bias * 60 * 1000;
return -bias * 60 * 1000;
#else
#else
time_t localTime = time(0);
time_t localTime = time(0);
tm localt;
tm localt;
getLocalTime(&localTime, &localt);
getLocalTime(&localTime, &localt);


// Get the difference between this time zone and UTC on the 1st of January of this year.
// Get the difference between this time zone and UTC on the 1st of January of this year.
localt.tm_sec = 0;
localt.tm_sec = 0;
localt.tm_min = 0;
localt.tm_min = 0;
localt.tm_hour = 0;
localt.tm_hour = 0;
localt.tm_mday = 1;
localt.tm_mday = 1;
localt.tm_mon = 0;
localt.tm_mon = 0;
// Not setting localt.tm_year!
// Not setting localt.tm_year!
localt.tm_wday = 0;
localt.tm_wday = 0;
localt.tm_yday = 0;
localt.tm_yday = 0;
localt.tm_isdst = 0;
localt.tm_isdst = 0;
#if HAVE(TM_GMTOFF)
#if HAVE(TM_GMTOFF)
localt.tm_gmtoff = 0;
localt.tm_gmtoff = 0;
#endif
#endif
#if HAVE(TM_ZONE)
#if HAVE(TM_ZONE)
localt.tm_zone = 0;
localt.tm_zone = 0;
#endif
#endif


#if HAVE(TIMEGM)
#if HAVE(TIMEGM)
time_t utcOffset = timegm(&localt) - mktime(&localt);
time_t utcOffset = timegm(&localt) - mktime(&localt);
#else
#else
// Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
// Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
localt.tm_year = 109;
localt.tm_year = 109;
time_t utcOffset = 1230768000 - mktime(&localt);
time_t utcOffset = 1230768000 - mktime(&localt);
#endif
#endif


return static_cast<int32_t>(utcOffset * 1000);
return static_cast<int32_t>(utcOffset * 1000);
#endif
#endif
}
}


#if !HAVE(TM_GMTOFF)

#if OS(WINDOWS)
// Code taken from http://support.microsoft.com/kb/167296
static void UnixTimeToFileTime(time_t t, LPFILETIME pft)
{
// Note that LONGLONG is a 64-bit value
LONGLONG ll;

ll = Int32x32To64(t, 10000000) + 116444736000000000;
pft->dwLowDateTime = (DWORD)ll;
pft->dwHighDateTime = ll >> 32;
}
#endif

/*
/*
* Get the DST offset for the time passed in.
* Get the DST offset for the time passed in.
*/
*/
static double calculateDSTOffset(time_t localTime, double utcOffset)
static double calculateDSTOffset(time_t localTime, double utcOffset)
{
{
#if OS(WINDOWS)
#if OS(WINCE)
FILETIME utcFileTime;
UNUSED_PARAM(localTime);
UnixTimeToFileTime(localTime, &utcFileTime);
UNUSED_PARAM(utcOffset);
SYSTEMTIME utcSystemTime, localSystemTime;
return 0;
if (!::FileTimeToSystemTime(&utcFileTime, &utcSystemTime))
return 0;
if (!::SystemTimeToTzSpecificLocalTime(nullptr, &utcSystemTime, &localSystemTime))
return 0;

double offsetTime = (localTime * msPerSecond) + utcOffset;

// Offset from UTC but doesn't include DST obviously
int offsetHour = msToHours(offsetTime);
int offsetMinute = msToMinutes(offsetTime);

double diff = ((localSystemTime.wHour - offsetHour) * secondsPerHour) + ((localSystemTime.wMinute - offsetMinute) * 60);

return diff * msPerSecond;
#else
#else
//input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
//input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
double offsetTime = (localTime * msPerSecond) + utcOffset;
double offsetTime = (localTime * msPerSecond) + utcOffset;


// Offset from UTC but doesn't include DST obviously
// Offset from UTC but doesn't include DST obviously
int offsetHour = msToHours(offsetTime);
int offsetHour = msToHours(offsetTime);
int offsetMinute = msToMinutes(offsetTime);
int offsetMinute = msToMinutes(offsetTime);


tm localTM;
tm localTM;
getLocalTime(&localTime, &localTM);
getLocalTime(&localTime, &localTM);


double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);


if (diff < 0)
if (diff < 0)
diff += secondsPerDay;
diff += secondsPerDay;


return (diff * msPerSecond);
return (diff * msPerSecond);
#endif
#endif
}
}


#endif
#endif


// Returns combined offset in millisecond (UTC + DST).
// Returns combined offset in millisecond (UTC + DST).
LocalTimeOffset calculateLocalTimeOffset(double ms, TimeType inputTimeType)
LocalTimeOffset calculateLocalTimeOffset(double ms)
{
{
#if HAVE(TM_GMTOFF)
double localToUTCTimeOffset = inputTimeType == LocalTime ? calculateUTCOffset() : 0;
#else
double localToUTCTimeOffset = calculateUTCOffset();
#endif
if (inputTimeType == LocalTime)
ms -= localToUTCTimeOffset;

// On Mac OS X, the call to localtime (see calculateDSTOffset) will return historically accurate
// On Mac OS X, the call to localtime (see calculateDSTOffset) will return historically accurate
// DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
// DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
// standard explicitly dictates that historical information should not be considered when
// standard explicitly dictates that historical information should not be considered when
// determining DST. For this reason we shift away from years that localtime can handle but would
// determining DST. For this reason we shift away from years that localtime can handle but would
// return historically accurate information.
// return historically accurate information.
int year = msToYear(ms);
int year = msToYear(ms);
int equivalentYear = equivalentYearForDST(year);
int equivalentYear = equivalentYearForDST(year);
if (year != equivalentYear) {
if (year != equivalentYear) {
bool leapYear = isLeapYear(year);
bool leapYear = isLeapYear(year);
int dayInYearLocal = dayInYear(ms, year);
int dayInYearLocal = dayInYear(ms, year);
int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
int month = monthFromDayInYear(dayInYearLocal, leapYear);
int month = monthFromDayInYear(dayInYearLocal, leapYear);
double day = dateToDaysFrom1970(equivalentYear, month, dayInMonth);
double day = dateToDaysFrom1970(equivalentYear, month, dayInMonth);
ms = (day * msPerDay) + msToMilliseconds(ms);
ms = (day * msPerDay) + msToMilliseconds(ms);
}
}


double localTimeSeconds = ms / msPerSecond;
double localTimeSeconds = ms / msPerSecond;
if (localTimeSeconds > maxUnixTime)
if (localTimeSeconds > maxUnixTime)
localTimeSeconds = maxUnixTime;
localTimeSeconds = maxUnixTime;
else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0).
else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0).
localTimeSeconds += secondsPerDay;
localTimeSeconds += secondsPerDay;
// FIXME: time_t has a potential problem in 2038.
// FIXME: time_t has a potential problem in 2038.
time_t localTime = static_cast<time_t>(localTimeSeconds);
time_t localTime = static_cast<time_t>(localTimeSeconds);


#if HAVE(TM_GMTOFF)
#if HAVE(TM_GMTOFF)
tm localTM;
tm localTM;
getLocalTime(&localTime, &localTM);
getLocalTime(&localTime, &localTM);
return LocalTimeOffset(localTM.tm_isdst, localTM.tm_gmtoff * msPerSecond);
return LocalTimeOffset(localTM.tm_isdst, localTM.tm_gmtoff * msPerSecond);
#else
#else
double dstOffset = calculateDSTOffset(localTime, localToUTCTimeOffset);
double utcOffset = calculateUTCOffset();
return LocalTimeOffset(dstOffset, localToUTCTimeOffset + dstOffset);
double dstOffset = calculateDSTOffset(localTime, utcOffset);
return LocalTimeOffset(dstOffset, utcOffset + dstOffset);
#endif
#endif
}
}


void initializeDates()
void initializeDates()
{
{
#if !ASSERT_DISABLED
#if !ASSERT_DISABLED
static bool alreadyInitialized;
static bool alreadyInitialized;
ASSERT(!alreadyInitialized);
ASSERT(!alreadyInitialized);
alreadyInitialized = true;
alreadyInitialized = true;
#endif
#endif


equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
}
}


static inline double ymdhmsToSeconds(int year, long mon, long day, long hour, long minute, double second)
static inline double ymdhmsToSeconds(int year, long mon, long day, long hour, long minute, double second)
{
{
int mday = firstDayOfMonth[isLeapYear(year)][mon - 1];
double days = (day - 32075)
double ydays = daysFrom1970ToYear(year);
+ floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)

+ 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
return (second + minute * secondsPerMinute + hour * secondsPerHour + (mday + day - 1 + ydays) * secondsPerDay);
- floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
- 2440588;
return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
}
}


// We follow the recommendation of RFC 2822 to consider all
// We follow the recommendation of RFC 2822 to consider all
// obsolete time zones not listed here equivalent to "-0000".
// obsolete time zones not listed here equivalent to "-0000".
static const struct KnownZone {
static const struct KnownZone {
#if !OS(WINDOWS)
#if !OS(WINDOWS)
const
const
#endif
#endif
char tzName[4];
char tzName[4];
int tzOffset;
int tzOffset;
} known_zones[] = {
} known_zones[] = {
{ "UT", 0 },
{ "UT", 0 },
{ "GMT", 0 },
{ "GMT", 0 },
{ "EST", -300 },
{ "EST", -300 },
{ "EDT", -240 },
{ "EDT", -240 },
{ "CST", -360 },
{ "CST", -360 },
{ "CDT", -300 },
{ "CDT", -300 },
{ "MST", -420 },
{ "MST", -420 },
{ "MDT", -360 },
{ "MDT", -360 },
{ "PST", -480 },
{ "PST", -480 },
{ "PDT", -420 }
{ "PDT", -420 }
};
};


inline static void skipSpacesAndComments(const char*& s)
inline static void skipSpacesAndComments(const char*& s)
{
{
int nesting = 0;
int nesting = 0;
char ch;
char ch;
while ((ch = *s)) {
while ((ch = *s)) {
if (!isASCIISpace(ch)) {
if (!isASCIISpace(ch)) {
if (ch == '(')
if (ch == '(')
nesting++;
nesting++;
else if (ch == ')' && nesting > 0)
else if (ch == ')' && nesting > 0)
nesting--;
nesting--;
else if (nesting == 0)
else if (nesting == 0)
break;
break;
}
}
s++;
s++;
}
}
}
}


// returns 0-11 (Jan-Dec); -1 on failure
// returns 0-11 (Jan-Dec); -1 on failure
static int findMonth(const char* monthStr)
static int findMonth(const char* monthStr)
{
{
ASSERT(monthStr);
ASSERT(monthStr);
char needle[4];
char needle[4];
for (int i = 0; i < 3; ++i) {
for (int i = 0; i < 3; ++i) {
if (!*monthStr)
if (!*monthStr)
return -1;
return -1;
needle[i] = static_cast<char>(toASCIILower(*monthStr++));
needle[i] = static_cast<char>(toASCIILower(*monthStr++));
}
}
needle[3] = '\0';
needle[3] = '\0';
const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
const char *str = strstr(haystack, needle);
const char *str = strstr(haystack, needle);
if (str) {
if (str) {
int position = static_cast<int>(str - haystack);
int position = static_cast<int>(str - haystack);
if (position % 3 == 0)
if (position % 3 == 0)
return position / 3;
return position / 3;
}
}
return -1;
return -1;
}
}


static bool parseInt(const char* string, char** stopPosition, int base, int* result)
static bool parseInt(const char* string, char** stopPosition, int base, int* result)
{
{
long longResult = strtol(string, stopPosition, base);
long longResult = strtol(string, stopPosition, base);
// Avoid the use of errno as it is not available on Windows CE
// Avoid the use of errno as it is not available on Windows CE
if (string == *stopPosition || longResult <= std::numeric_limits<int>::min() || longResult >= std::numeric_limits<int>::max())
if (string == *stopPosition || longResult <= std::numeric_limits<int>::min() || longResult >= std::numeric_limits<int>::max())
return false;
return false;
*result = static_cast<int>(longResult);
*result = static_cast<int>(longResult);
return true;
return true;
}
}


static bool parseLong(const char* string, char** stopPosition, int base, long* result)
static bool parseLong(const char* string, char** stopPosition, int base, long* result)
{
{
*result = strtol(string, stopPosition, base);
*result = strtol(string, stopPosition, base);
// Avoid the use of errno as it is not available on Windows CE
// Avoid the use of errno as it is not available on Windows CE
if (string == *stopPosition || *result == std::numeric_limits<long>::min() || *result == std::numeric_limits<long>::max())
if (string == *stopPosition || *result == std::numeric_limits<long>::min() || *result == std::numeric_limits<long>::max())
return false;
return false;
return true;
return true;
}
}


// Parses a date with the format YYYY[-MM[-DD]].
// Parses a date with the format YYYY[-MM[-DD]].
// Year parsing is lenient, allows any number of digits, and +/-.
// Year parsing is lenient, allows any number of digits, and +/-.
// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
static char* parseES5DatePortion(const char* currentPosition, int& year, long& month, long& day)
static char* parseES5DatePortion(const char* currentPosition, int& year, long& month, long& day)
{
{
char* postParsePosition;
char* postParsePosition;


// This is a bit more lenient on the year string than ES5 specifies:
// This is a bit more lenient on the year string than ES5 specifies:
// instead of restricting to 4 digits (or 6 digits with mandatory +/-),
// instead of restricting to 4 digits (or 6 digits with mandatory +/-),
// it accepts any integer value. Consider this an implementation fallback.
// it accepts any integer value. Consider this an implementation fallback.
if (!parseInt(currentPosition, &postParsePosition, 10, &year))
if (!parseInt(currentPosition, &postParsePosition, 10, &year))
return 0;
return 0;


// Check for presence of -MM portion.
// Check for presence of -MM portion.
if (*postParsePosition != '-')
if (*postParsePosition != '-')
return postParsePosition;
return postParsePosition;
currentPosition = postParsePosition + 1;
currentPosition = postParsePosition + 1;
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &month))
if (!parseLong(currentPosition, &postParsePosition, 10, &month))
return 0;
return 0;
if ((postParsePosition - currentPosition) != 2)
if ((postParsePosition - currentPosition) != 2)
return 0;
return 0;


// Check for presence of -DD portion.
// Check for presence of -DD portion.
if (*postParsePosition != '-')
if (*postParsePosition != '-')
return postParsePosition;
return postParsePosition;
currentPosition = postParsePosition + 1;
currentPosition = postParsePosition + 1;
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &day))
if (!parseLong(currentPosition, &postParsePosition, 10, &day))
return 0;
return 0;
if ((postParsePosition - currentPosition) != 2)
if ((postParsePosition - currentPosition) != 2)
return 0;
return 0;
return postParsePosition;
return postParsePosition;
}
}


// Parses a time with the format HH:mm[:ss[.sss]][Z|(+|-)00:00].
// Parses a time with the format HH:mm[:ss[.sss]][Z|(+|-)00:00].
// Fractional seconds parsing is lenient, allows any number of digits.
// Fractional seconds parsing is lenient, allows any number of digits.
// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
// Returns 0 if a parse error occurs, else returns the end of the parsed portion of the string.
static char* parseES5TimePortion(char* currentPosition, long& hours, long& minutes, double& seconds, long& timeZoneSeconds)
static char* parseES5TimePortion(char* currentPosition, long& hours, long& minutes, double& seconds, long& timeZoneSeconds)
{
{
char* postParsePosition;
char* postParsePosition;
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &hours))
if (!parseLong(currentPosition, &postParsePosition, 10, &hours))
return 0;
return 0;
if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2)
if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2)
return 0;
return 0;
currentPosition = postParsePosition + 1;
currentPosition = postParsePosition + 1;
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &minutes))
if (!parseLong(currentPosition, &postParsePosition, 10, &minutes))
return 0;
return 0;
if ((postParsePosition - currentPosition) != 2)
if ((postParsePosition - currentPosition) != 2)
return 0;
return 0;
currentPosition = postParsePosition;
currentPosition = postParsePosition;


// Seconds are optional.
// Seconds are optional.
if (*currentPosition == ':') {
if (*currentPosition == ':') {
++currentPosition;
++currentPosition;
long intSeconds;
long intSeconds;
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &intSeconds))
if (!parseLong(currentPosition, &postParsePosition, 10, &intSeconds))
return 0;
return 0;
if ((postParsePosition - currentPosition) != 2)
if ((postParsePosition - currentPosition) != 2)
return 0;
return 0;
seconds = intSeconds;
seconds = intSeconds;
if (*postParsePosition == '.') {
if (*postParsePosition == '.') {
currentPosition = postParsePosition + 1;
currentPosition = postParsePosition + 1;
// In ECMA-262-5 it's a bit unclear if '.' can be present without milliseconds, but
// In ECMA-262-5 it's a bit unclear if '.' can be present without milliseconds, but
// a reasonable interpretation guided by the given examples and RFC 3339 says "no".
// a reasonable interpretation guided by the given examples and RFC 3339 says "no".
// We check the next character to avoid reading +/- timezone hours after an invalid decimal.
// We check the next character to avoid reading +/- timezone hours after an invalid decimal.
if (!isASCIIDigit(*currentPosition))
if (!isASCIIDigit(*currentPosition))
return 0;
return 0;
// We are more lenient than ES5 by accepting more or less than 3 fraction digits.
// We are more lenient than ES5 by accepting more or less than 3 fraction digits.
long fracSeconds;
long fracSeconds;
if (!parseLong(currentPosition, &postParsePosition, 10, &fracSeconds))
if (!parseLong(currentPosition, &postParsePosition, 10, &fracSeconds))
return 0;
return 0;
long numFracDigits = postParsePosition - currentPosition;
long numFracDigits = postParsePosition - currentPosition;
seconds += fracSeconds * pow(10.0, static_cast<double>(-numFracDigits));
seconds += fracSeconds * pow(10.0, static_cast<double>(-numFracDigits));
}
}
currentPosition = postParsePosition;
currentPosition = postParsePosition;
}
}


if (*currentPosition == 'Z')
if (*currentPosition == 'Z')
return currentPosition + 1;
return currentPosition + 1;


bool tzNegative;
bool tzNegative;
if (*currentPosition == '-')
if (*currentPosition == '-')
tzNegative = true;
tzNegative = true;
else if (*currentPosition == '+')
else if (*currentPosition == '+')
tzNegative = false;
tzNegative = false;
else
else
return currentPosition; // no timezone
return currentPosition; // no timezone
++currentPositi
++currentPosition;
long tzHours;
long tzHoursAbs;
long tzMinutes;
if (!isASCIIDigit(*currentPosition))
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &tzHours))
return 0;
if (*postParsePosition != ':' || (postParsePosition - currentPosition) != 2)
return 0;
tzHoursAbs = labs(tzHours);
currentPosition = postParsePosition + 1;
if (!isASCIIDigit(*currentPosition))
return 0;
if (!parseLong(currentPosition, &postParsePosition, 10, &tzMinutes))
return 0;
if ((postParsePosition - currentPosition) != 2)
return 0;
currentPosition = postParsePosition;
if (tzHoursAbs > 24)
return 0;
if (tzMinutes < 0 || tzMinutes > 59)
return 0;
timeZoneSeconds = 60 * (tzMinutes + (60 * tzHoursAbs));
if (tzNegative)
timeZoneSeconds = -timeZoneSeconds;

return currentPosition;
}

double parseES5DateFromNullTerminatedCharacters(const char* dateString)
{
// This parses a date of the form defined in ECMA-262-5, section 15.9.1.15
// (similar to RFC 3339 / ISO 8601: YYYY-MM-DDTHH:mm:ss[.sss]Z).
// In most cases it is intentionally strict (e.g. correct field widths, no stray whitespace).
static const long daysPerMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// The year must be present, but the other fields may be omitted - see ES5.1 15.9.1.15.
int year = 0;
long month = 1;
long day = 1;
long hours = 0;
long minutes = 0;
double seconds = 0;
long timeZoneSeconds = 0;

// Parse the date YYYY[-MM[-DD]]
char* currentPosition = parseES5DatePortion(dateString, year, month, day);
if (!currentPosition)
return std::numeric_limits<double>::quiet_NaN();
// Look for a time portion.
if (*currentPosition == 'T') {
// Parse the time HH:mm[:ss[.sss]][Z|(+|-)00:00]
currentPosition = parseES5TimePortion(currentPosition + 1, hours, minutes, seconds, timeZoneSeconds);
if (!currentPosition)
return std::numeric_limits<double>::quiet_NaN();
}
// Check that we have parsed all characters in the string.
if (*currentPosition)
return std::numeric_limits<double>