blob: 47c9d4415f43045bd429260a4634e7e01f5834a4 [file] [log] [blame]
kmccullod129ead2006-10-04 18:36:29 +00001/*
2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
darinb5a0e3d2007-01-10 00:08:18 +00003 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +00004 * Copyright (C) 2009 Google Inc. All rights reserved.
5 *
kmccullod129ead2006-10-04 18:36:29 +00006 * The Original Code is Mozilla Communicator client code, released
7 * March 31, 1998.
8 *
9 * The Initial Developer of the Original Code is
10 * Netscape Communications Corporation.
11 * Portions created by the Initial Developer are Copyright (C) 1998
12 * the Initial Developer. All Rights Reserved.
13 *
darinc8c684a2007-01-30 22:07:21 +000014 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Lesser General Public
16 * License as published by the Free Software Foundation; either
17 * version 2.1 of the License, or (at your option) any later version.
kmccullod129ead2006-10-04 18:36:29 +000018 *
darinc8c684a2007-01-30 22:07:21 +000019 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Lesser General Public License for more details.
kmccullod129ead2006-10-04 18:36:29 +000023 *
darinc8c684a2007-01-30 22:07:21 +000024 * You should have received a copy of the GNU Lesser General Public
25 * License along with this library; if not, write to the Free Software
ddkilzerc8eccec2007-09-26 02:29:57 +000026 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
darinc8c684a2007-01-30 22:07:21 +000027 *
28 * Alternatively, the contents of this file may be used under the terms
29 * of either the Mozilla Public License Version 1.1, found at
30 * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
31 * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
32 * (the "GPL"), in which case the provisions of the MPL or the GPL are
33 * applicable instead of those above. If you wish to allow use of your
34 * version of this file only under the terms of one of those two
35 * licenses (the MPL or the GPL) and not to allow others to use your
36 * version of this file under the LGPL, indicate your decision by
37 * deletingthe provisions above and replace them with the notice and
38 * other provisions required by the MPL or the GPL, as the case may be.
39 * If you do not delete the provisions above, a recipient may use your
40 * version of this file under any of the LGPL, the MPL or the GPL.
kmccullod129ead2006-10-04 18:36:29 +000041 */
42
kmccullodee1af22006-10-13 18:56:41 +000043#include "config.h"
44#include "DateMath.h"
kmccullod129ead2006-10-04 18:36:29 +000045
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +000046#include "Assertions.h"
47#include "ASCIICType.h"
48#include "CurrentTime.h"
49#include "MathExtras.h"
50#include "StringExtras.h"
51
dglazkov@chromium.org003a1272009-06-08 23:16:04 +000052#include <algorithm>
mrowe@apple.com29711302009-06-09 04:48:45 +000053#include <limits.h>
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +000054#include <limits>
kmccullod129ead2006-10-04 18:36:29 +000055#include <stdint.h>
weinig@apple.comb54ef442008-06-29 19:53:42 +000056#include <time.h>
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +000057
darin3bb15072007-03-02 17:42:20 +000058
weinig@apple.com747bcd92008-06-29 22:18:38 +000059#if HAVE(ERRNO_H)
60#include <errno.h>
61#endif
62
darin3bb15072007-03-02 17:42:20 +000063#if PLATFORM(DARWIN)
64#include <notify.h>
65#endif
kmccullod129ead2006-10-04 18:36:29 +000066
bdash16e4c702007-03-15 13:26:45 +000067#if HAVE(SYS_TIME_H)
68#include <sys/time.h>
69#endif
70
kmcculloe4255dd2007-03-15 03:23:56 +000071#if HAVE(SYS_TIMEB_H)
72#include <sys/timeb.h>
73#endif
74
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +000075#define NaN std::numeric_limits<double>::quiet_NaN()
weinig@apple.com603e4d122008-06-29 20:21:04 +000076
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +000077namespace WTF {
kmccullod129ead2006-10-04 18:36:29 +000078
79/* Constants */
80
kmccullod129ead2006-10-04 18:36:29 +000081static const double minutesPerDay = 24.0 * 60.0;
82static const double secondsPerDay = 24.0 * 60.0 * 60.0;
83static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
84
kmccullod129ead2006-10-04 18:36:29 +000085static const double usecPerSec = 1000000.0;
86
darin3bb15072007-03-02 17:42:20 +000087static const double maxUnixTime = 2145859200.0; // 12/31/2037
kmccullod129ead2006-10-04 18:36:29 +000088
darin3bb15072007-03-02 17:42:20 +000089// Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
90// First for non-leap years, then for leap years.
91static const int firstDayOfMonth[2][12] = {
kmccullob0e322b2006-10-04 20:35:58 +000092 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
93 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
kmccullod129ead2006-10-04 18:36:29 +000094};
95
darin3bb15072007-03-02 17:42:20 +000096static inline bool isLeapYear(int year)
kmccullod129ead2006-10-04 18:36:29 +000097{
98 if (year % 4 != 0)
darin3bb15072007-03-02 17:42:20 +000099 return false;
kmccullod129ead2006-10-04 18:36:29 +0000100 if (year % 400 == 0)
darin3bb15072007-03-02 17:42:20 +0000101 return true;
kmccullod129ead2006-10-04 18:36:29 +0000102 if (year % 100 == 0)
darin3bb15072007-03-02 17:42:20 +0000103 return false;
104 return true;
105}
106
107static inline int daysInYear(int year)
108{
109 return 365 + isLeapYear(year);
kmccullod129ead2006-10-04 18:36:29 +0000110}
111
112static inline double daysFrom1970ToYear(int year)
113{
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000114 // The Gregorian Calendar rules for leap years:
115 // Every fourth year is a leap year. 2004, 2008, and 2012 are leap years.
116 // However, every hundredth year is not a leap year. 1900 and 2100 are not leap years.
117 // Every four hundred years, there's a leap year after all. 2000 and 2400 are leap years.
kmccullod129ead2006-10-04 18:36:29 +0000118
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000119 static const int leapDaysBefore1971By4Rule = 1970 / 4;
120 static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
121 static const int leapDaysBefore1971By400Rule = 1970 / 400;
122
123 const double yearMinusOne = year - 1;
124 const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
125 const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
126 const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
127
128 return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
kmccullod129ead2006-10-04 18:36:29 +0000129}
130
kmccullob0e322b2006-10-04 20:35:58 +0000131static inline double msToDays(double ms)
kmccullod129ead2006-10-04 18:36:29 +0000132{
133 return floor(ms / msPerDay);
134}
135
kmccullo03524ba2006-10-04 21:08:43 +0000136static inline int msToYear(double ms)
kmccullod129ead2006-10-04 18:36:29 +0000137{
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000138 int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
139 double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
140 if (msFromApproxYearTo1970 > ms)
141 return approxYear - 1;
142 if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
143 return approxYear + 1;
144 return approxYear;
kmccullod129ead2006-10-04 18:36:29 +0000145}
146
kmccullo03524ba2006-10-04 21:08:43 +0000147static inline int dayInYear(double ms, int year)
kmccullod129ead2006-10-04 18:36:29 +0000148{
kmccullo03524ba2006-10-04 21:08:43 +0000149 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
kmccullod129ead2006-10-04 18:36:29 +0000150}
151
152static inline double msToMilliseconds(double ms)
153{
darin3bb15072007-03-02 17:42:20 +0000154 double result = fmod(ms, msPerDay);
kmccullod129ead2006-10-04 18:36:29 +0000155 if (result < 0)
156 result += msPerDay;
157 return result;
158}
159
160// 0: Sunday, 1: Monday, etc.
161static inline int msToWeekDay(double ms)
162{
darin3bb15072007-03-02 17:42:20 +0000163 int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
kmccullod129ead2006-10-04 18:36:29 +0000164 if (wd < 0)
165 wd += 7;
166 return wd;
167}
168
169static inline int msToSeconds(double ms)
170{
darin3bb15072007-03-02 17:42:20 +0000171 double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
kmccullod129ead2006-10-04 18:36:29 +0000172 if (result < 0)
darin3bb15072007-03-02 17:42:20 +0000173 result += secondsPerMinute;
174 return static_cast<int>(result);
kmccullod129ead2006-10-04 18:36:29 +0000175}
176
177static inline int msToMinutes(double ms)
178{
darin3bb15072007-03-02 17:42:20 +0000179 double result = fmod(floor(ms / msPerMinute), minutesPerHour);
kmccullod129ead2006-10-04 18:36:29 +0000180 if (result < 0)
darin3bb15072007-03-02 17:42:20 +0000181 result += minutesPerHour;
182 return static_cast<int>(result);
kmccullod129ead2006-10-04 18:36:29 +0000183}
184
185static inline int msToHours(double ms)
186{
darin3bb15072007-03-02 17:42:20 +0000187 double result = fmod(floor(ms/msPerHour), hoursPerDay);
kmccullod129ead2006-10-04 18:36:29 +0000188 if (result < 0)
darin3bb15072007-03-02 17:42:20 +0000189 result += hoursPerDay;
190 return static_cast<int>(result);
kmccullod129ead2006-10-04 18:36:29 +0000191}
192
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000193static inline int monthFromDayInYear(int dayInYear, bool leapYear)
kmccullod129ead2006-10-04 18:36:29 +0000194{
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000195 const int d = dayInYear;
darin3bb15072007-03-02 17:42:20 +0000196 int step;
kmccullod129ead2006-10-04 18:36:29 +0000197
198 if (d < (step = 31))
199 return 0;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000200 step += (leapYear ? 29 : 28);
kmccullod129ead2006-10-04 18:36:29 +0000201 if (d < step)
202 return 1;
203 if (d < (step += 31))
204 return 2;
205 if (d < (step += 30))
206 return 3;
207 if (d < (step += 31))
208 return 4;
209 if (d < (step += 30))
210 return 5;
211 if (d < (step += 31))
212 return 6;
213 if (d < (step += 31))
214 return 7;
215 if (d < (step += 30))
216 return 8;
217 if (d < (step += 31))
218 return 9;
219 if (d < (step += 30))
220 return 10;
221 return 11;
222}
223
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000224static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
kmccullod129ead2006-10-04 18:36:29 +0000225{
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000226 startDayOfThisMonth = startDayOfNextMonth;
227 startDayOfNextMonth += daysInThisMonth;
228 return (dayInYear <= startDayOfNextMonth);
229}
kmccullod129ead2006-10-04 18:36:29 +0000230
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000231static inline int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
232{
233 const int d = dayInYear;
234 int step;
235 int next = 30;
236
kmccullod129ead2006-10-04 18:36:29 +0000237 if (d <= next)
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000238 return d + 1;
239 const int daysInFeb = (leapYear ? 29 : 28);
240 if (checkMonth(d, step, next, daysInFeb))
kmccullod129ead2006-10-04 18:36:29 +0000241 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000242 if (checkMonth(d, step, next, 31))
kmccullod129ead2006-10-04 18:36:29 +0000243 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000244 if (checkMonth(d, step, next, 30))
kmccullod129ead2006-10-04 18:36:29 +0000245 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000246 if (checkMonth(d, step, next, 31))
kmccullod129ead2006-10-04 18:36:29 +0000247 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000248 if (checkMonth(d, step, next, 30))
kmccullod129ead2006-10-04 18:36:29 +0000249 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000250 if (checkMonth(d, step, next, 31))
kmccullod129ead2006-10-04 18:36:29 +0000251 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000252 if (checkMonth(d, step, next, 31))
kmccullod129ead2006-10-04 18:36:29 +0000253 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000254 if (checkMonth(d, step, next, 30))
kmccullod129ead2006-10-04 18:36:29 +0000255 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000256 if (checkMonth(d, step, next, 31))
kmccullod129ead2006-10-04 18:36:29 +0000257 return d - step;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000258 if (checkMonth(d, step, next, 30))
kmccullod129ead2006-10-04 18:36:29 +0000259 return d - step;
260 step = next;
261 return d - step;
262}
263
kmccullob0e322b2006-10-04 20:35:58 +0000264static inline int monthToDayInYear(int month, bool isLeapYear)
kmccullod129ead2006-10-04 18:36:29 +0000265{
266 return firstDayOfMonth[isLeapYear][month];
267}
268
kmccullo54552172006-10-12 17:58:09 +0000269static inline double timeToMS(double hour, double min, double sec, double ms)
kmccullod129ead2006-10-04 18:36:29 +0000270{
271 return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
272}
273
kmccullob0e322b2006-10-04 20:35:58 +0000274static int dateToDayInYear(int year, int month, int day)
kmccullod129ead2006-10-04 18:36:29 +0000275{
kmccullofd1a9a42006-10-05 00:19:21 +0000276 year += month / 12;
kmccullod129ead2006-10-04 18:36:29 +0000277
kmccullofd1a9a42006-10-05 00:19:21 +0000278 month %= 12;
279 if (month < 0) {
kmccullod129ead2006-10-04 18:36:29 +0000280 month += 12;
kmccullofd1a9a42006-10-05 00:19:21 +0000281 --year;
282 }
kmccullod129ead2006-10-04 18:36:29 +0000283
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000284 int yearday = static_cast<int>(floor(daysFrom1970ToYear(year)));
kmccullob0e322b2006-10-04 20:35:58 +0000285 int monthday = monthToDayInYear(month, isLeapYear(year));
kmccullod129ead2006-10-04 18:36:29 +0000286
287 return yearday + monthday + day - 1;
288}
289
kmccullo014b4532007-03-15 02:21:47 +0000290double getCurrentUTCTime()
291{
timothy@apple.com7de48b22008-05-20 13:58:12 +0000292 return floor(getCurrentUTCTimeWithMicroseconds());
293}
294
ap@webkit.orgc01ff492009-01-11 08:14:58 +0000295// Returns current time in milliseconds since 1 Jan 1970.
timothy@apple.com7de48b22008-05-20 13:58:12 +0000296double getCurrentUTCTimeWithMicroseconds()
297{
ap@webkit.orgc01ff492009-01-11 08:14:58 +0000298 return currentTime() * 1000.0;
kmccullo014b4532007-03-15 02:21:47 +0000299}
300
ap@webkit.orgd8a20fb2008-03-14 14:59:38 +0000301void getLocalTime(const time_t* localTime, struct tm* localTM)
302{
treat@webkit.org068b0692009-06-17 16:39:56 +0000303#if COMPILER(MSVC7) || COMPILER(MINGW) || PLATFORM(WINCE)
hausmann@webkit.org3e76bf42008-07-16 10:14:03 +0000304 *localTM = *localtime(localTime);
hausmann@webkit.org33d7cdd2008-07-17 12:01:57 +0000305#elif COMPILER(MSVC)
hausmann@webkit.org3e76bf42008-07-16 10:14:03 +0000306 localtime_s(localTM, localTime);
ap@webkit.orgd8a20fb2008-03-14 14:59:38 +0000307#else
308 localtime_r(localTime, localTM);
309#endif
310}
311
kmccullo014b4532007-03-15 02:21:47 +0000312// There is a hard limit at 2038 that we currently do not have a workaround
313// for (rdar://problem/5052975).
314static inline int maximumYearForDST()
315{
316 return 2037;
317}
318
alp@webkit.org7e5b9702008-10-20 17:10:41 +0000319static inline int minimumYearForDST()
kmccullo014b4532007-03-15 02:21:47 +0000320{
321 // Because of the 2038 issue (see maximumYearForDST) if the current year is
322 // greater than the max year minus 27 (2010), we want to use the max year
323 // minus 27 instead, to ensure there is a range of 28 years that all years
324 // can map to.
ap@webkit.org7d34b912008-04-11 16:40:15 +0000325 return std::min(msToYear(getCurrentUTCTime()), maximumYearForDST() - 27) ;
kmccullo014b4532007-03-15 02:21:47 +0000326}
327
kmccullod129ead2006-10-04 18:36:29 +0000328/*
kmccullo014b4532007-03-15 02:21:47 +0000329 * Find an equivalent year for the one given, where equivalence is deterined by
330 * the two years having the same leapness and the first day of the year, falling
331 * on the same day of the week.
kmccullod129ead2006-10-04 18:36:29 +0000332 *
kmccullo014b4532007-03-15 02:21:47 +0000333 * This function returns a year between this current year and 2037, however this
334 * function will potentially return incorrect results if the current year is after
335 * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
336 * 2100, (rdar://problem/5055038).
kmccullod129ead2006-10-04 18:36:29 +0000337 */
weiniga1da4752006-10-26 18:27:47 +0000338int equivalentYearForDST(int year)
kmccullod129ead2006-10-04 18:36:29 +0000339{
ap@webkit.org7d34b912008-04-11 16:40:15 +0000340 // It is ok if the cached year is not the current year as long as the rules
341 // for DST did not change between the two years; if they did the app would need
342 // to be restarted.
alp@webkit.org7e5b9702008-10-20 17:10:41 +0000343 static int minYear = minimumYearForDST();
ap@webkit.org7d34b912008-04-11 16:40:15 +0000344 int maxYear = maximumYearForDST();
beidson@apple.comb3c7b2b2008-04-08 21:28:08 +0000345
kmccullo014b4532007-03-15 02:21:47 +0000346 int difference;
347 if (year > maxYear)
348 difference = minYear - year;
349 else if (year < minYear)
350 difference = maxYear - year;
351 else
352 return year;
353
354 int quotient = difference / 28;
355 int product = (quotient) * 28;
356
357 year += product;
358 ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
359 return year;
kmccullod129ead2006-10-04 18:36:29 +0000360}
361
ap@webkit.org7d34b912008-04-11 16:40:15 +0000362static int32_t calculateUTCOffset()
363{
barraclough@apple.comce9bf692009-06-19 05:06:55 +0000364 time_t localTime = time(0);
ap@webkit.org7d34b912008-04-11 16:40:15 +0000365 tm localt;
barraclough@apple.comce9bf692009-06-19 05:06:55 +0000366 getLocalTime(&localTime, &localt);
367
368 // Get the difference between this time zone and UTC on the 1st of January of this year.
369 localt.tm_sec = 0;
370 localt.tm_min = 0;
371 localt.tm_hour = 0;
ap@webkit.org7d34b912008-04-11 16:40:15 +0000372 localt.tm_mday = 1;
barraclough@apple.comce9bf692009-06-19 05:06:55 +0000373 localt.tm_mon = 0;
374 // Not setting localt.tm_year!
375 localt.tm_wday = 0;
376 localt.tm_yday = 0;
377 localt.tm_isdst = 0;
barraclough@apple.com071fb662009-06-19 05:39:59 +0000378#if PLATFORM(WIN_OS) || PLATFORM(SOLARIS) || COMPILER(RVCT)
379 // Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
380 localt.tm_year = 109;
381 time_t utcOffset = 1230768000 - mktime(&localt);
382#else
barraclough@apple.comce9bf692009-06-19 05:06:55 +0000383 localt.tm_zone = 0;
384 localt.tm_gmtoff = 0;
385 time_t utcOffset = timegm(&localt) - mktime(&localt);
barraclough@apple.com071fb662009-06-19 05:39:59 +0000386#endif
ap@webkit.org7d34b912008-04-11 16:40:15 +0000387
388 return static_cast<int32_t>(utcOffset * 1000);
389}
390
391#if PLATFORM(DARWIN)
392static int32_t s_cachedUTCOffset; // In milliseconds. An assumption here is that access to an int32_t variable is atomic on platforms that take this code path.
393static bool s_haveCachedUTCOffset;
394static int s_notificationToken;
395#endif
396
kmccullod129ead2006-10-04 18:36:29 +0000397/*
398 * Get the difference in milliseconds between this time zone and UTC (GMT)
399 * NOT including DST.
400 */
darin3bb15072007-03-02 17:42:20 +0000401double getUTCOffset()
402{
403#if PLATFORM(DARWIN)
ap@webkit.org7d34b912008-04-11 16:40:15 +0000404 if (s_haveCachedUTCOffset) {
darin3bb15072007-03-02 17:42:20 +0000405 int notified;
ap@webkit.org7d34b912008-04-11 16:40:15 +0000406 uint32_t status = notify_check(s_notificationToken, &notified);
darin3bb15072007-03-02 17:42:20 +0000407 if (status == NOTIFY_STATUS_OK && !notified)
ap@webkit.org7d34b912008-04-11 16:40:15 +0000408 return s_cachedUTCOffset;
darin3bb15072007-03-02 17:42:20 +0000409 }
410#endif
411
ap@webkit.org7d34b912008-04-11 16:40:15 +0000412 int32_t utcOffset = calculateUTCOffset();
kmccullod129ead2006-10-04 18:36:29 +0000413
darin3bb15072007-03-02 17:42:20 +0000414#if PLATFORM(DARWIN)
ap@webkit.org7d34b912008-04-11 16:40:15 +0000415 // Theoretically, it is possible that several threads will be executing this code at once, in which case we will have a race condition,
416 // and a newer value may be overwritten. In practice, time zones don't change that often.
417 s_cachedUTCOffset = utcOffset;
darin3bb15072007-03-02 17:42:20 +0000418#endif
419
kmccullod129ead2006-10-04 18:36:29 +0000420 return utcOffset;
421}
422
423/*
424 * Get the DST offset for the time passed in. Takes
425 * seconds (not milliseconds) and cannot handle dates before 1970
426 * on some OS'
427 */
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000428static double getDSTOffsetSimple(double localTimeSeconds, double utcOffset)
kmccullod129ead2006-10-04 18:36:29 +0000429{
darin3bb15072007-03-02 17:42:20 +0000430 if (localTimeSeconds > maxUnixTime)
kmccullod129ead2006-10-04 18:36:29 +0000431 localTimeSeconds = maxUnixTime;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000432 else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
kmccullofc463452006-10-06 18:16:38 +0000433 localTimeSeconds += secondsPerDay;
kmccullod129ead2006-10-04 18:36:29 +0000434
kmccullob7aacf52006-11-01 20:34:23 +0000435 //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000436 double offsetTime = (localTimeSeconds * msPerSecond) + utcOffset;
kmccullofc463452006-10-06 18:16:38 +0000437
kmccullo54552172006-10-12 17:58:09 +0000438 // Offset from UTC but doesn't include DST obviously
439 int offsetHour = msToHours(offsetTime);
440 int offsetMinute = msToMinutes(offsetTime);
kmccullod129ead2006-10-04 18:36:29 +0000441
kmccullob0e322b2006-10-04 20:35:58 +0000442 // FIXME: time_t has a potential problem in 2038
443 time_t localTime = static_cast<time_t>(localTimeSeconds);
kmccullod129ead2006-10-04 18:36:29 +0000444
kmcculloa1376152006-10-13 17:31:11 +0000445 tm localTM;
ap@webkit.orgd8a20fb2008-03-14 14:59:38 +0000446 getLocalTime(&localTime, &localTM);
darin3bb15072007-03-02 17:42:20 +0000447
kmcculloa1376152006-10-13 17:31:11 +0000448 double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
kmccullod129ead2006-10-04 18:36:29 +0000449
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000450 if (diff < 0)
kmccullod129ead2006-10-04 18:36:29 +0000451 diff += secondsPerDay;
452
kmccullo4fef9f72006-10-18 17:37:04 +0000453 return (diff * msPerSecond);
kmccullod129ead2006-10-04 18:36:29 +0000454}
455
darin3bb15072007-03-02 17:42:20 +0000456// Get the DST offset, given a time in UTC
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000457static double getDSTOffset(double ms, double utcOffset)
kmccullod129ead2006-10-04 18:36:29 +0000458{
darin3bb15072007-03-02 17:42:20 +0000459 // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
kmccullob7aacf52006-11-01 20:34:23 +0000460 // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
461 // standard explicitly dictates that historical information should not be considered when
darin3bb15072007-03-02 17:42:20 +0000462 // determining DST. For this reason we shift away from years that localtime can handle but would
kmccullob7aacf52006-11-01 20:34:23 +0000463 // return historically accurate information.
kmccullo014b4532007-03-15 02:21:47 +0000464 int year = msToYear(ms);
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000465 int equivalentYear = equivalentYearForDST(year);
466 if (year != equivalentYear) {
467 bool leapYear = isLeapYear(year);
468 int dayInYearLocal = dayInYear(ms, year);
469 int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
470 int month = monthFromDayInYear(dayInYearLocal, leapYear);
471 int day = dateToDayInYear(equivalentYear, month, dayInMonth);
kmccullod129ead2006-10-04 18:36:29 +0000472 ms = (day * msPerDay) + msToMilliseconds(ms);
473 }
474
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000475 return getDSTOffsetSimple(ms / msPerSecond, utcOffset);
kmccullod129ead2006-10-04 18:36:29 +0000476}
477
kmcculloa1376152006-10-13 17:31:11 +0000478double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
kmccullod129ead2006-10-04 18:36:29 +0000479{
kmcculloa1376152006-10-13 17:31:11 +0000480 int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
481 double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
kmccullo54552172006-10-12 17:58:09 +0000482 double result = (day * msPerDay) + ms;
kmccullod129ead2006-10-04 18:36:29 +0000483
darin3bb15072007-03-02 17:42:20 +0000484 if (!inputIsUTC) { // convert to UTC
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000485 double utcOffset = getUTCOffset();
486 result -= utcOffset;
487 result -= getDSTOffset(result, utcOffset);
kmccullofc463452006-10-06 18:16:38 +0000488 }
kmccullod129ead2006-10-04 18:36:29 +0000489
490 return result;
491}
492
aroben6181d052007-03-02 19:55:21 +0000493void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
kmccullod129ead2006-10-04 18:36:29 +0000494{
kmccullofc463452006-10-06 18:16:38 +0000495 // input is UTC
496 double dstOff = 0.0;
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000497 const double utcOff = getUTCOffset();
beidson@apple.comb3c7b2b2008-04-08 21:28:08 +0000498
darin3bb15072007-03-02 17:42:20 +0000499 if (!outputIsUTC) { // convert to local time
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000500 dstOff = getDSTOffset(ms, utcOff);
501 ms += dstOff + utcOff;
kmccullofc463452006-10-06 18:16:38 +0000502 }
kmccullod129ead2006-10-04 18:36:29 +0000503
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000504 const int year = msToYear(ms);
kmcculloa1376152006-10-13 17:31:11 +0000505 tm.second = msToSeconds(ms);
506 tm.minute = msToMinutes(ms);
507 tm.hour = msToHours(ms);
508 tm.weekDay = msToWeekDay(ms);
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000509 tm.yearDay = dayInYear(ms, year);
510 tm.monthDay = dayInMonthFromDayInYear(tm.yearDay, isLeapYear(year));
511 tm.month = monthFromDayInYear(tm.yearDay, isLeapYear(year));
512 tm.year = year - 1900;
darin3bb15072007-03-02 17:42:20 +0000513 tm.isDST = dstOff != 0.0;
kmccullod129ead2006-10-04 18:36:29 +0000514
eric@webkit.org3dcd6f52007-12-20 22:46:41 +0000515 tm.utcOffset = static_cast<long>((dstOff + utcOff) / msPerSecond);
kmcculloa1376152006-10-13 17:31:11 +0000516 tm.timeZone = NULL;
kmccullod129ead2006-10-04 18:36:29 +0000517}
518
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000519void initializeDates()
ap@webkit.org7d34b912008-04-11 16:40:15 +0000520{
521#ifndef NDEBUG
522 static bool alreadyInitialized;
523 ASSERT(!alreadyInitialized++);
524#endif
525
526 equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
527#if PLATFORM(DARWIN)
528 // Register for a notification whenever the time zone changes.
529 uint32_t status = notify_register_check("com.apple.system.timezone", &s_notificationToken);
530 if (status == NOTIFY_STATUS_OK) {
531 s_cachedUTCOffset = calculateUTCOffset();
532 s_haveCachedUTCOffset = true;
533 }
534#endif
535}
536
weinig@apple.comb54ef442008-06-29 19:53:42 +0000537static inline double ymdhmsToSeconds(long year, int mon, int day, int hour, int minute, int second)
538{
539 double days = (day - 32075)
540 + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
541 + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
542 - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
543 - 2440588;
544 return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
545}
546
547// We follow the recommendation of RFC 2822 to consider all
548// obsolete time zones not listed here equivalent to "-0000".
549static const struct KnownZone {
550#if !PLATFORM(WIN_OS)
551 const
552#endif
553 char tzName[4];
554 int tzOffset;
555} known_zones[] = {
556 { "UT", 0 },
557 { "GMT", 0 },
558 { "EST", -300 },
559 { "EDT", -240 },
560 { "CST", -360 },
561 { "CDT", -300 },
562 { "MST", -420 },
563 { "MDT", -360 },
564 { "PST", -480 },
565 { "PDT", -420 }
566};
567
568inline static void skipSpacesAndComments(const char*& s)
569{
570 int nesting = 0;
571 char ch;
572 while ((ch = *s)) {
573 if (!isASCIISpace(ch)) {
574 if (ch == '(')
575 nesting++;
576 else if (ch == ')' && nesting > 0)
577 nesting--;
578 else if (nesting == 0)
579 break;
580 }
581 s++;
582 }
583}
584
585// returns 0-11 (Jan-Dec); -1 on failure
586static int findMonth(const char* monthStr)
587{
588 ASSERT(monthStr);
589 char needle[4];
590 for (int i = 0; i < 3; ++i) {
591 if (!*monthStr)
592 return -1;
593 needle[i] = static_cast<char>(toASCIILower(*monthStr++));
594 }
595 needle[3] = '\0';
596 const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
597 const char *str = strstr(haystack, needle);
598 if (str) {
599 int position = static_cast<int>(str - haystack);
600 if (position % 3 == 0)
601 return position / 3;
602 }
603 return -1;
604}
605
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000606static bool parseLong(const char* string, char** stopPosition, int base, long* result)
607{
608 *result = strtol(string, stopPosition, base);
609 // Avoid the use of errno as it is not available on Windows CE
610 if (string == *stopPosition || *result == LONG_MIN || *result == LONG_MAX)
611 return false;
612 return true;
613}
614
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000615double parseDateFromNullTerminatedCharacters(const char* dateString)
weinig@apple.comb54ef442008-06-29 19:53:42 +0000616{
617 // This parses a date in the form:
618 // Tuesday, 09-Nov-99 23:12:40 GMT
619 // or
620 // Sat, 01-Jan-2000 08:00:00 GMT
621 // or
622 // Sat, 01 Jan 2000 08:00:00 GMT
623 // or
624 // 01 Jan 99 22:00 +0100 (exceptions in rfc822/rfc2822)
625 // ### non RFC formats, added for Javascript:
626 // [Wednesday] January 09 1999 23:12:40 GMT
627 // [Wednesday] January 09 23:12:40 GMT 1999
628 //
629 // We ignore the weekday.
weinig@apple.comb54ef442008-06-29 19:53:42 +0000630
631 // Skip leading space
632 skipSpacesAndComments(dateString);
633
634 long month = -1;
635 const char *wordStart = dateString;
636 // Check contents of first words if not number
637 while (*dateString && !isASCIIDigit(*dateString)) {
638 if (isASCIISpace(*dateString) || *dateString == '(') {
639 if (dateString - wordStart >= 3)
640 month = findMonth(wordStart);
641 skipSpacesAndComments(dateString);
642 wordStart = dateString;
643 } else
644 dateString++;
645 }
646
647 // Missing delimiter between month and day (like "January29")?
648 if (month == -1 && wordStart != dateString)
649 month = findMonth(wordStart);
650
651 skipSpacesAndComments(dateString);
652
653 if (!*dateString)
654 return NaN;
655
656 // ' 09-Nov-99 23:12:40 GMT'
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000657 char* newPosStr;
658 long day;
659 if (!parseLong(dateString, &newPosStr, 10, &day))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000660 return NaN;
661 dateString = newPosStr;
662
663 if (!*dateString)
664 return NaN;
665
666 if (day < 0)
667 return NaN;
668
669 long year = 0;
670 if (day > 31) {
671 // ### where is the boundary and what happens below?
672 if (*dateString != '/')
673 return NaN;
674 // looks like a YYYY/MM/DD date
675 if (!*++dateString)
676 return NaN;
677 year = day;
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000678 if (!parseLong(dateString, &newPosStr, 10, &month))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000679 return NaN;
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000680 month -= 1;
weinig@apple.comb54ef442008-06-29 19:53:42 +0000681 dateString = newPosStr;
682 if (*dateString++ != '/' || !*dateString)
683 return NaN;
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000684 if (!parseLong(dateString, &newPosStr, 10, &day))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000685 return NaN;
686 dateString = newPosStr;
687 } else if (*dateString == '/' && month == -1) {
688 dateString++;
689 // This looks like a MM/DD/YYYY date, not an RFC date.
690 month = day - 1; // 0-based
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000691 if (!parseLong(dateString, &newPosStr, 10, &day))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000692 return NaN;
693 if (day < 1 || day > 31)
694 return NaN;
695 dateString = newPosStr;
696 if (*dateString == '/')
697 dateString++;
698 if (!*dateString)
699 return NaN;
700 } else {
701 if (*dateString == '-')
702 dateString++;
703
704 skipSpacesAndComments(dateString);
705
706 if (*dateString == ',')
707 dateString++;
708
709 if (month == -1) { // not found yet
710 month = findMonth(dateString);
711 if (month == -1)
712 return NaN;
713
714 while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
715 dateString++;
716
717 if (!*dateString)
718 return NaN;
719
720 // '-99 23:12:40 GMT'
721 if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
722 return NaN;
723 dateString++;
724 }
725 }
726
727 if (month < 0 || month > 11)
728 return NaN;
729
730 // '99 23:12:40 GMT'
731 if (year <= 0 && *dateString) {
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000732 if (!parseLong(dateString, &newPosStr, 10, &year))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000733 return NaN;
734 }
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000735
weinig@apple.comb54ef442008-06-29 19:53:42 +0000736 // Don't fail if the time is missing.
737 long hour = 0;
738 long minute = 0;
739 long second = 0;
740 if (!*newPosStr)
741 dateString = newPosStr;
742 else {
743 // ' 23:12:40 GMT'
744 if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
745 if (*newPosStr != ':')
746 return NaN;
747 // There was no year; the number was the hour.
748 year = -1;
749 } else {
750 // in the normal case (we parsed the year), advance to the next number
751 dateString = ++newPosStr;
752 skipSpacesAndComments(dateString);
753 }
754
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000755 parseLong(dateString, &newPosStr, 10, &hour);
weinig@apple.comb54ef442008-06-29 19:53:42 +0000756 // Do not check for errno here since we want to continue
757 // even if errno was set becasue we are still looking
758 // for the timezone!
759
760 // Read a number? If not, this might be a timezone name.
761 if (newPosStr != dateString) {
762 dateString = newPosStr;
763
764 if (hour < 0 || hour > 23)
765 return NaN;
766
767 if (!*dateString)
768 return NaN;
769
770 // ':12:40 GMT'
771 if (*dateString++ != ':')
772 return NaN;
773
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000774 if (!parseLong(dateString, &newPosStr, 10, &minute))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000775 return NaN;
776 dateString = newPosStr;
777
778 if (minute < 0 || minute > 59)
779 return NaN;
780
781 // ':40 GMT'
782 if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
783 return NaN;
784
785 // seconds are optional in rfc822 + rfc2822
786 if (*dateString ==':') {
787 dateString++;
788
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000789 if (!parseLong(dateString, &newPosStr, 10, &second))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000790 return NaN;
791 dateString = newPosStr;
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000792
weinig@apple.comb54ef442008-06-29 19:53:42 +0000793 if (second < 0 || second > 59)
794 return NaN;
795 }
796
797 skipSpacesAndComments(dateString);
798
799 if (strncasecmp(dateString, "AM", 2) == 0) {
800 if (hour > 12)
801 return NaN;
802 if (hour == 12)
803 hour = 0;
804 dateString += 2;
805 skipSpacesAndComments(dateString);
806 } else if (strncasecmp(dateString, "PM", 2) == 0) {
807 if (hour > 12)
808 return NaN;
809 if (hour != 12)
810 hour += 12;
811 dateString += 2;
812 skipSpacesAndComments(dateString);
813 }
814 }
815 }
816
817 bool haveTZ = false;
818 int offset = 0;
819
820 // Don't fail if the time zone is missing.
821 // Some websites omit the time zone (4275206).
822 if (*dateString) {
823 if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
824 dateString += 3;
825 haveTZ = true;
826 }
827
828 if (*dateString == '+' || *dateString == '-') {
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000829 long o;
830 if (!parseLong(dateString, &newPosStr, 10, &o))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000831 return NaN;
832 dateString = newPosStr;
833
834 if (o < -9959 || o > 9959)
835 return NaN;
836
837 int sgn = (o < 0) ? -1 : 1;
838 o = abs(o);
839 if (*dateString != ':') {
840 offset = ((o / 100) * 60 + (o % 100)) * sgn;
841 } else { // GMT+05:00
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000842 long o2;
843 if (!parseLong(dateString, &newPosStr, 10, &o2))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000844 return NaN;
845 dateString = newPosStr;
846 offset = (o * 60 + o2) * sgn;
847 }
848 haveTZ = true;
849 } else {
850 for (int i = 0; i < int(sizeof(known_zones) / sizeof(KnownZone)); i++) {
851 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
852 offset = known_zones[i].tzOffset;
853 dateString += strlen(known_zones[i].tzName);
854 haveTZ = true;
855 break;
856 }
857 }
858 }
859 }
860
861 skipSpacesAndComments(dateString);
862
863 if (*dateString && year == -1) {
hausmann@webkit.org409c2ad2008-11-28 15:19:09 +0000864 if (!parseLong(dateString, &newPosStr, 10, &year))
weinig@apple.comb54ef442008-06-29 19:53:42 +0000865 return NaN;
866 dateString = newPosStr;
867 }
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000868
weinig@apple.comb54ef442008-06-29 19:53:42 +0000869 skipSpacesAndComments(dateString);
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000870
weinig@apple.comb54ef442008-06-29 19:53:42 +0000871 // Trailing garbage
872 if (*dateString)
873 return NaN;
874
875 // Y2K: Handle 2 digit years.
876 if (year >= 0 && year < 100) {
877 if (year < 50)
878 year += 2000;
879 else
880 year += 1900;
881 }
882
883 // fall back to local timezone
884 if (!haveTZ) {
885 GregorianDateTime t;
886 t.monthDay = day;
887 t.month = month;
888 t.year = year - 1900;
889 t.isDST = -1;
890 t.second = second;
891 t.minute = minute;
892 t.hour = hour;
893
894 // Use our gregorianDateTimeToMS() rather than mktime() as the latter can't handle the full year range.
895 return gregorianDateTimeToMS(t, 0, false);
896 }
897
898 return (ymdhmsToSeconds(year, month + 1, day, hour, minute, second) - (offset * 60.0)) * msPerSecond;
899}
900
901double timeClip(double t)
902{
903 if (!isfinite(t))
904 return NaN;
905 if (fabs(t) > 8.64E15)
906 return NaN;
907 return trunc(t);
908}
909
weinig@apple.comb54ef442008-06-29 19:53:42 +0000910
dglazkov@chromium.org1d2d8742009-06-08 22:37:06 +0000911} // namespace WTF