source: webkit/trunk/JavaScriptCore/kjs/DateMath.cpp@ 31737

Last change on this file since 31737 was 31737, checked in by [email protected], 17 years ago

Strongly encourage Windows bots to rebuild with DOM_STORAGE enabled

  • Property svn:eol-style set to native
File size: 15.5 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
4 *
5 * The Original Code is Mozilla Communicator client code, released
6 * March 31, 1998.
7 *
8 * The Initial Developer of the Original Code is
9 * Netscape Communications Corporation.
10 * Portions created by the Initial Developer are Copyright (C) 1998
11 * the Initial Developer. All Rights Reserved.
12 *
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Lesser General Public
15 * License as published by the Free Software Foundation; either
16 * version 2.1 of the License, or (at your option) any later version.
17 *
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Lesser General Public License for more details.
22 *
23 * You should have received a copy of the GNU Lesser General Public
24 * License along with this library; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 *
27 * Alternatively, the contents of this file may be used under the terms
28 * of either the Mozilla Public License Version 1.1, found at
29 * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
30 * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
31 * (the "GPL"), in which case the provisions of the MPL or the GPL are
32 * applicable instead of those above. If you wish to allow use of your
33 * version of this file only under the terms of one of those two
34 * licenses (the MPL or the GPL) and not to allow others to use your
35 * version of this file under the LGPL, indicate your decision by
36 * deletingthe provisions above and replace them with the notice and
37 * other provisions required by the MPL or the GPL, as the case may be.
38 * If you do not delete the provisions above, a recipient may use your
39 * version of this file under any of the LGPL, the MPL or the GPL.
40 */
41
42#include "config.h"
43#include "DateMath.h"
44
45#include <math.h>
46#include <stdint.h>
47#include <value.h>
48
49#include <wtf/Assertions.h>
50
51#if PLATFORM(DARWIN)
52#include <notify.h>
53#endif
54
55#if HAVE(SYS_TIME_H)
56#include <sys/time.h>
57#endif
58
59#if HAVE(SYS_TIMEB_H)
60#include <sys/timeb.h>
61#endif
62
63namespace KJS {
64
65/* Constants */
66
67static const double minutesPerDay = 24.0 * 60.0;
68static const double secondsPerDay = 24.0 * 60.0 * 60.0;
69static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
70
71static const double usecPerSec = 1000000.0;
72
73static const double maxUnixTime = 2145859200.0; // 12/31/2037
74
75// Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
76// First for non-leap years, then for leap years.
77static const int firstDayOfMonth[2][12] = {
78 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
79 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
80};
81
82static inline bool isLeapYear(int year)
83{
84 if (year % 4 != 0)
85 return false;
86 if (year % 400 == 0)
87 return true;
88 if (year % 100 == 0)
89 return false;
90 return true;
91}
92
93static inline int daysInYear(int year)
94{
95 return 365 + isLeapYear(year);
96}
97
98static inline double daysFrom1970ToYear(int year)
99{
100 // The Gregorian Calendar rules for leap years:
101 // Every fourth year is a leap year. 2004, 2008, and 2012 are leap years.
102 // However, every hundredth year is not a leap year. 1900 and 2100 are not leap years.
103 // Every four hundred years, there's a leap year after all. 2000 and 2400 are leap years.
104
105 static const int leapDaysBefore1971By4Rule = 1970 / 4;
106 static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
107 static const int leapDaysBefore1971By400Rule = 1970 / 400;
108
109 const double yearMinusOne = year - 1;
110 const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
111 const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
112 const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
113
114 return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
115}
116
117static inline double msToDays(double ms)
118{
119 return floor(ms / msPerDay);
120}
121
122static inline int msToYear(double ms)
123{
124 int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
125 double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
126 if (msFromApproxYearTo1970 > ms)
127 return approxYear - 1;
128 if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
129 return approxYear + 1;
130 return approxYear;
131}
132
133static inline int dayInYear(double ms, int year)
134{
135 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
136}
137
138static inline double msToMilliseconds(double ms)
139{
140 double result = fmod(ms, msPerDay);
141 if (result < 0)
142 result += msPerDay;
143 return result;
144}
145
146// 0: Sunday, 1: Monday, etc.
147static inline int msToWeekDay(double ms)
148{
149 int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
150 if (wd < 0)
151 wd += 7;
152 return wd;
153}
154
155static inline int msToSeconds(double ms)
156{
157 double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
158 if (result < 0)
159 result += secondsPerMinute;
160 return static_cast<int>(result);
161}
162
163static inline int msToMinutes(double ms)
164{
165 double result = fmod(floor(ms / msPerMinute), minutesPerHour);
166 if (result < 0)
167 result += minutesPerHour;
168 return static_cast<int>(result);
169}
170
171static inline int msToHours(double ms)
172{
173 double result = fmod(floor(ms/msPerHour), hoursPerDay);
174 if (result < 0)
175 result += hoursPerDay;
176 return static_cast<int>(result);
177}
178
179static inline int monthFromDayInYear(int dayInYear, bool leapYear)
180{
181 const int d = dayInYear;
182 int step;
183
184 if (d < (step = 31))
185 return 0;
186 step += (leapYear ? 29 : 28);
187 if (d < step)
188 return 1;
189 if (d < (step += 31))
190 return 2;
191 if (d < (step += 30))
192 return 3;
193 if (d < (step += 31))
194 return 4;
195 if (d < (step += 30))
196 return 5;
197 if (d < (step += 31))
198 return 6;
199 if (d < (step += 31))
200 return 7;
201 if (d < (step += 30))
202 return 8;
203 if (d < (step += 31))
204 return 9;
205 if (d < (step += 30))
206 return 10;
207 return 11;
208}
209
210static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
211{
212 startDayOfThisMonth = startDayOfNextMonth;
213 startDayOfNextMonth += daysInThisMonth;
214 return (dayInYear <= startDayOfNextMonth);
215}
216
217static inline int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
218{
219 const int d = dayInYear;
220 int step;
221 int next = 30;
222
223 if (d <= next)
224 return d + 1;
225 const int daysInFeb = (leapYear ? 29 : 28);
226 if (checkMonth(d, step, next, daysInFeb))
227 return d - step;
228 if (checkMonth(d, step, next, 31))
229 return d - step;
230 if (checkMonth(d, step, next, 30))
231 return d - step;
232 if (checkMonth(d, step, next, 31))
233 return d - step;
234 if (checkMonth(d, step, next, 30))
235 return d - step;
236 if (checkMonth(d, step, next, 31))
237 return d - step;
238 if (checkMonth(d, step, next, 31))
239 return d - step;
240 if (checkMonth(d, step, next, 30))
241 return d - step;
242 if (checkMonth(d, step, next, 31))
243 return d - step;
244 if (checkMonth(d, step, next, 30))
245 return d - step;
246 step = next;
247 return d - step;
248}
249
250static inline int monthToDayInYear(int month, bool isLeapYear)
251{
252 return firstDayOfMonth[isLeapYear][month];
253}
254
255static inline double timeToMS(double hour, double min, double sec, double ms)
256{
257 return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
258}
259
260static int dateToDayInYear(int year, int month, int day)
261{
262 year += month / 12;
263
264 month %= 12;
265 if (month < 0) {
266 month += 12;
267 --year;
268 }
269
270 int yearday = static_cast<int>(floor(daysFrom1970ToYear(year)));
271 int monthday = monthToDayInYear(month, isLeapYear(year));
272
273 return yearday + monthday + day - 1;
274}
275
276double getCurrentUTCTime()
277{
278#if PLATFORM(WIN_OS)
279#if COMPILER(BORLAND)
280 struct timeb timebuffer;
281 ftime(&timebuffer);
282#else
283 struct _timeb timebuffer;
284 _ftime(&timebuffer);
285#endif
286 double utc = timebuffer.time * msPerSecond + timebuffer.millitm;
287#else
288 struct timeval tv;
289 gettimeofday(&tv, 0);
290 double utc = floor(tv.tv_sec * msPerSecond + tv.tv_usec / 1000);
291#endif
292 return utc;
293}
294
295void getLocalTime(const time_t* localTime, struct tm* localTM)
296{
297#if PLATFORM(QT)
298#if USE(MULTIPLE_THREADS)
299#error Mulitple threads are currently not supported in the Qt/mingw build
300#endif
301 *localTM = *localtime(localTime);
302#elif PLATFORM(WIN_OS)
303 #if COMPILER(MSVC7)
304 *localTM = *localtime(localTime);
305 #else
306 localtime_s(localTM, localTime);
307 #endif
308#else
309 localtime_r(localTime, localTM);
310#endif
311}
312
313// There is a hard limit at 2038 that we currently do not have a workaround
314// for (rdar://problem/5052975).
315static inline int maximumYearForDST()
316{
317 return 2037;
318}
319
320// It is ok if the cached year is not the current year (e.g. Dec 31st)
321// so long as the rules for DST did not change between the two years, if it does
322// the app would need to be restarted.
323static int mimimumYearForDST()
324{
325 // Because of the 2038 issue (see maximumYearForDST) if the current year is
326 // greater than the max year minus 27 (2010), we want to use the max year
327 // minus 27 instead, to ensure there is a range of 28 years that all years
328 // can map to.
329 static int minYear = std::min(msToYear(getCurrentUTCTime()), maximumYearForDST() - 27) ;
330 return minYear;
331}
332
333/*
334 * Find an equivalent year for the one given, where equivalence is deterined by
335 * the two years having the same leapness and the first day of the year, falling
336 * on the same day of the week.
337 *
338 * This function returns a year between this current year and 2037, however this
339 * function will potentially return incorrect results if the current year is after
340 * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
341 * 2100, (rdar://problem/5055038).
342 */
343int equivalentYearForDST(int year)
344{
345 static int minYear = mimimumYearForDST();
346 static int maxYear = maximumYearForDST();
347
348 int difference;
349 if (year > maxYear)
350 difference = minYear - year;
351 else if (year < minYear)
352 difference = maxYear - year;
353 else
354 return year;
355
356 int quotient = difference / 28;
357 int product = (quotient) * 28;
358
359 year += product;
360 ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
361 return year;
362}
363
364/*
365 * Get the difference in milliseconds between this time zone and UTC (GMT)
366 * NOT including DST.
367 */
368double getUTCOffset()
369{
370#if PLATFORM(DARWIN)
371 // Register for a notification whenever the time zone changes.
372 static bool triedToRegister = false;
373 static bool haveNotificationToken = false;
374 static int notificationToken;
375 if (!triedToRegister) {
376 triedToRegister = true;
377 uint32_t status = notify_register_check("com.apple.system.timezone", &notificationToken);
378 if (status == NOTIFY_STATUS_OK)
379 haveNotificationToken = true;
380 }
381
382 // If we can verify that we have not received a time zone notification,
383 // then use the cached offset from the last time this function was called.
384 static bool haveCachedOffset = false;
385 static double cachedOffset;
386 if (haveNotificationToken && haveCachedOffset) {
387 int notified;
388 uint32_t status = notify_check(notificationToken, &notified);
389 if (status == NOTIFY_STATUS_OK && !notified)
390 return cachedOffset;
391 }
392#endif
393
394 tm localt;
395
396 memset(&localt, 0, sizeof(localt));
397
398 // get the difference between this time zone and UTC on Jan 01, 2000 12:00:00 AM
399 localt.tm_mday = 1;
400 localt.tm_year = 100;
401 double utcOffset = 946684800.0 - mktime(&localt);
402
403 utcOffset *= msPerSecond;
404
405#if PLATFORM(DARWIN)
406 haveCachedOffset = true;
407 cachedOffset = utcOffset;
408#endif
409
410 return utcOffset;
411}
412
413/*
414 * Get the DST offset for the time passed in. Takes
415 * seconds (not milliseconds) and cannot handle dates before 1970
416 * on some OS'
417 */
418static double getDSTOffsetSimple(double localTimeSeconds, double utcOffset)
419{
420 if (localTimeSeconds > maxUnixTime)
421 localTimeSeconds = maxUnixTime;
422 else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
423 localTimeSeconds += secondsPerDay;
424
425 //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
426 double offsetTime = (localTimeSeconds * msPerSecond) + utcOffset;
427
428 // Offset from UTC but doesn't include DST obviously
429 int offsetHour = msToHours(offsetTime);
430 int offsetMinute = msToMinutes(offsetTime);
431
432 // FIXME: time_t has a potential problem in 2038
433 time_t localTime = static_cast<time_t>(localTimeSeconds);
434
435 tm localTM;
436 getLocalTime(&localTime, &localTM);
437
438 double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
439
440 if (diff < 0)
441 diff += secondsPerDay;
442
443 return (diff * msPerSecond);
444}
445
446// Get the DST offset, given a time in UTC
447static double getDSTOffset(double ms, double utcOffset)
448{
449 // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
450 // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
451 // standard explicitly dictates that historical information should not be considered when
452 // determining DST. For this reason we shift away from years that localtime can handle but would
453 // return historically accurate information.
454 int year = msToYear(ms);
455 int equivalentYear = equivalentYearForDST(year);
456 if (year != equivalentYear) {
457 bool leapYear = isLeapYear(year);
458 int dayInYearLocal = dayInYear(ms, year);
459 int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
460 int month = monthFromDayInYear(dayInYearLocal, leapYear);
461 int day = dateToDayInYear(equivalentYear, month, dayInMonth);
462 ms = (day * msPerDay) + msToMilliseconds(ms);
463 }
464
465 return getDSTOffsetSimple(ms / msPerSecond, utcOffset);
466}
467
468double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
469{
470 int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
471 double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
472 double result = (day * msPerDay) + ms;
473
474 if (!inputIsUTC) { // convert to UTC
475 double utcOffset = getUTCOffset();
476 result -= utcOffset;
477 result -= getDSTOffset(result, utcOffset);
478 }
479
480 return result;
481}
482
483void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
484{
485 // input is UTC
486 double dstOff = 0.0;
487 const double utcOff = getUTCOffset();
488
489 if (!outputIsUTC) { // convert to local time
490 dstOff = getDSTOffset(ms, utcOff);
491 ms += dstOff + utcOff;
492 }
493
494 const int year = msToYear(ms);
495 tm.second = msToSeconds(ms);
496 tm.minute = msToMinutes(ms);
497 tm.hour = msToHours(ms);
498 tm.weekDay = msToWeekDay(ms);
499 tm.yearDay = dayInYear(ms, year);
500 tm.monthDay = dayInMonthFromDayInYear(tm.yearDay, isLeapYear(year));
501 tm.month = monthFromDayInYear(tm.yearDay, isLeapYear(year));
502 tm.year = year - 1900;
503 tm.isDST = dstOff != 0.0;
504
505 tm.utcOffset = static_cast<long>((dstOff + utcOff) / msPerSecond);
506 tm.timeZone = NULL;
507}
508
509} // namespace KJS
Note: See TracBrowser for help on using the repository browser.