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

Last change on this file since 24714 was 24714, checked in by hausmann, 18 years ago

Fix compilation with Qt on Windows with MingW: The MingW headers do not provide a prototype for a reentrant version of localtime. But since we don't use multiple threads for the Qt build we can use the plain localtime() function.

File size: 14.0 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 return 365.0 * (year - 1970)
101 + floor((year - 1969) / 4.0)
102 - floor((year - 1901) / 100.0)
103 + floor((year - 1601) / 400.0);
104}
105
106static inline double msFrom1970ToYear(int year)
107{
108 return msPerDay * daysFrom1970ToYear(year);
109}
110
111static inline double msToDays(double ms)
112{
113 return floor(ms / msPerDay);
114}
115
116static inline int msToYear(double ms)
117{
118 int y = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
119 double t2 = msFrom1970ToYear(y);
120 if (t2 > ms) {
121 y--;
122 } else {
123 if (t2 + msPerDay * daysInYear(y) <= ms)
124 y++;
125 }
126 return y;
127}
128
129static inline bool isInLeapYear(double ms)
130{
131 return isLeapYear(msToYear(ms));
132}
133
134static inline int dayInYear(double ms, int year)
135{
136 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
137}
138
139static inline double msToMilliseconds(double ms)
140{
141 double result = fmod(ms, msPerDay);
142 if (result < 0)
143 result += msPerDay;
144 return result;
145}
146
147// 0: Sunday, 1: Monday, etc.
148static inline int msToWeekDay(double ms)
149{
150 int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
151 if (wd < 0)
152 wd += 7;
153 return wd;
154}
155
156static inline int msToSeconds(double ms)
157{
158 double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
159 if (result < 0)
160 result += secondsPerMinute;
161 return static_cast<int>(result);
162}
163
164static inline int msToMinutes(double ms)
165{
166 double result = fmod(floor(ms / msPerMinute), minutesPerHour);
167 if (result < 0)
168 result += minutesPerHour;
169 return static_cast<int>(result);
170}
171
172static inline int msToHours(double ms)
173{
174 double result = fmod(floor(ms/msPerHour), hoursPerDay);
175 if (result < 0)
176 result += hoursPerDay;
177 return static_cast<int>(result);
178}
179
180static inline int msToMonth(double ms)
181{
182 int step;
183 int year = msToYear(ms);
184 int d = dayInYear(ms, year);
185
186 if (d < (step = 31))
187 return 0;
188 step += (isInLeapYear(ms) ? 29 : 28);
189 if (d < step)
190 return 1;
191 if (d < (step += 31))
192 return 2;
193 if (d < (step += 30))
194 return 3;
195 if (d < (step += 31))
196 return 4;
197 if (d < (step += 30))
198 return 5;
199 if (d < (step += 31))
200 return 6;
201 if (d < (step += 31))
202 return 7;
203 if (d < (step += 30))
204 return 8;
205 if (d < (step += 31))
206 return 9;
207 if (d < (step += 30))
208 return 10;
209 return 11;
210}
211
212static inline int msToDayInMonth(double ms)
213{
214 int step, next;
215 int year = msToYear(ms);
216 int d = dayInYear(ms, year);
217
218 if (d <= (next = 30))
219 return d + 1;
220 step = next;
221 next += (isInLeapYear(ms) ? 29 : 28);
222 if (d <= next)
223 return d - step;
224 step = next;
225 if (d <= (next += 31))
226 return d - step;
227 step = next;
228 if (d <= (next += 30))
229 return d - step;
230 step = next;
231 if (d <= (next += 31))
232 return d - step;
233 step = next;
234 if (d <= (next += 30))
235 return d - step;
236 step = next;
237 if (d <= (next += 31))
238 return d - step;
239 step = next;
240 if (d <= (next += 31))
241 return d - step;
242 step = next;
243 if (d <= (next += 30))
244 return d - step;
245 step = next;
246 if (d <= (next += 31))
247 return d - step;
248 step = next;
249 if (d <= (next += 30))
250 return d - step;
251 step = next;
252 return d - step;
253}
254
255static inline int monthToDayInYear(int month, bool isLeapYear)
256{
257 return firstDayOfMonth[isLeapYear][month];
258}
259
260static inline double timeToMS(double hour, double min, double sec, double ms)
261{
262 return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
263}
264
265static int dateToDayInYear(int year, int month, int day)
266{
267 year += month / 12;
268
269 month %= 12;
270 if (month < 0) {
271 month += 12;
272 --year;
273 }
274
275 int yearday = static_cast<int>(floor(msFrom1970ToYear(year) / msPerDay));
276 int monthday = monthToDayInYear(month, isLeapYear(year));
277
278 return yearday + monthday + day - 1;
279}
280
281double getCurrentUTCTime()
282{
283#if PLATFORM(WIN_OS)
284#if COMPILER(BORLAND)
285 struct timeb timebuffer;
286 ftime(&timebuffer);
287#else
288 struct _timeb timebuffer;
289 _ftime(&timebuffer);
290#endif
291 double utc = timebuffer.time * msPerSecond + timebuffer.millitm;
292#else
293 struct timeval tv;
294 gettimeofday(&tv, 0);
295 double utc = floor(tv.tv_sec * msPerSecond + tv.tv_usec / 1000);
296#endif
297 return utc;
298}
299
300// There is a hard limit at 2038 that we currently do not have a workaround
301// for (rdar://problem/5052975).
302static inline int maximumYearForDST()
303{
304 return 2037;
305}
306
307// It is ok if the cached year is not the current year (e.g. Dec 31st)
308// so long as the rules for DST did not change between the two years, if it does
309// the app would need to be restarted.
310static int mimimumYearForDST()
311{
312 // Because of the 2038 issue (see maximumYearForDST) if the current year is
313 // greater than the max year minus 27 (2010), we want to use the max year
314 // minus 27 instead, to ensure there is a range of 28 years that all years
315 // can map to.
316 static int minYear = std::min(msToYear(getCurrentUTCTime()), maximumYearForDST()-27) ;
317 return minYear;
318}
319
320/*
321 * Find an equivalent year for the one given, where equivalence is deterined by
322 * the two years having the same leapness and the first day of the year, falling
323 * on the same day of the week.
324 *
325 * This function returns a year between this current year and 2037, however this
326 * function will potentially return incorrect results if the current year is after
327 * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
328 * 2100, (rdar://problem/5055038).
329 */
330int equivalentYearForDST(int year)
331{
332 static int minYear = mimimumYearForDST();
333 static int maxYear = maximumYearForDST();
334
335 int difference;
336 if (year > maxYear)
337 difference = minYear - year;
338 else if (year < minYear)
339 difference = maxYear - year;
340 else
341 return year;
342
343 int quotient = difference / 28;
344 int product = (quotient) * 28;
345
346 year += product;
347 ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
348 return year;
349}
350
351/*
352 * Get the difference in milliseconds between this time zone and UTC (GMT)
353 * NOT including DST.
354 */
355double getUTCOffset()
356{
357#if PLATFORM(DARWIN)
358 // Register for a notification whenever the time zone changes.
359 static bool triedToRegister = false;
360 static bool haveNotificationToken = false;
361 static int notificationToken;
362 if (!triedToRegister) {
363 triedToRegister = true;
364 uint32_t status = notify_register_check("com.apple.system.timezone", &notificationToken);
365 if (status == NOTIFY_STATUS_OK)
366 haveNotificationToken = true;
367 }
368
369 // If we can verify that we have not received a time zone notification,
370 // then use the cached offset from the last time this function was called.
371 static bool haveCachedOffset = false;
372 static double cachedOffset;
373 if (haveNotificationToken && haveCachedOffset) {
374 int notified;
375 uint32_t status = notify_check(notificationToken, &notified);
376 if (status == NOTIFY_STATUS_OK && !notified)
377 return cachedOffset;
378 }
379#endif
380
381 tm localt;
382
383 memset(&localt, 0, sizeof(localt));
384
385 // get the difference between this time zone and UTC on Jan 01, 2000 12:00:00 AM
386 localt.tm_mday = 1;
387 localt.tm_year = 100;
388 double utcOffset = 946684800.0 - mktime(&localt);
389
390 utcOffset *= msPerSecond;
391
392#if PLATFORM(DARWIN)
393 haveCachedOffset = true;
394 cachedOffset = utcOffset;
395#endif
396
397 return utcOffset;
398}
399
400/*
401 * Get the DST offset for the time passed in. Takes
402 * seconds (not milliseconds) and cannot handle dates before 1970
403 * on some OS'
404 */
405static double getDSTOffsetSimple(double localTimeSeconds)
406{
407 if (localTimeSeconds > maxUnixTime)
408 localTimeSeconds = maxUnixTime;
409 else if(localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
410 localTimeSeconds += secondsPerDay;
411
412 //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
413 double offsetTime = (localTimeSeconds * msPerSecond) + getUTCOffset();
414
415 // Offset from UTC but doesn't include DST obviously
416 int offsetHour = msToHours(offsetTime);
417 int offsetMinute = msToMinutes(offsetTime);
418
419 // FIXME: time_t has a potential problem in 2038
420 time_t localTime = static_cast<time_t>(localTimeSeconds);
421
422 tm localTM;
423#if PLATFORM(QT)
424 // ### this is not threadsafe but we don't use multiple threads anyway
425 // in the Qt build
426#if USE(MULTIPLE_THREADS)
427#error Mulitple threads are currently not supported in the Qt/mingw build
428#endif
429 localTM = *localtime(&localTime);
430#elif PLATFORM(WIN_OS)
431 localtime_s(&localTM, &localTime);
432#else
433 localtime_r(&localTime, &localTM);
434#endif
435
436 double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
437
438 if(diff < 0)
439 diff += secondsPerDay;
440
441 return (diff * msPerSecond);
442}
443
444// Get the DST offset, given a time in UTC
445static double getDSTOffset(double ms)
446{
447 // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
448 // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
449 // standard explicitly dictates that historical information should not be considered when
450 // determining DST. For this reason we shift away from years that localtime can handle but would
451 // return historically accurate information.
452 int year = msToYear(ms);
453 int equvalentYear = equivalentYearForDST(year);
454 if (year != equvalentYear) {
455 int day = dateToDayInYear(equvalentYear, msToMonth(ms), msToDayInMonth(ms));
456 ms = (day * msPerDay) + msToMilliseconds(ms);
457 }
458
459 return getDSTOffsetSimple(ms / msPerSecond);
460}
461
462double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
463{
464 int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
465 double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
466 double result = (day * msPerDay) + ms;
467
468 if (!inputIsUTC) { // convert to UTC
469 result -= getUTCOffset();
470 result -= getDSTOffset(result);
471 }
472
473 return result;
474}
475
476void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
477{
478 // input is UTC
479 double dstOff = 0.0;
480
481 if (!outputIsUTC) { // convert to local time
482 dstOff = getDSTOffset(ms);
483 ms += dstOff + getUTCOffset();
484 }
485
486 tm.second = msToSeconds(ms);
487 tm.minute = msToMinutes(ms);
488 tm.hour = msToHours(ms);
489 tm.weekDay = msToWeekDay(ms);
490 tm.monthDay = msToDayInMonth(ms);
491 tm.yearDay = dayInYear(ms, msToYear(ms));
492 tm.month = msToMonth(ms);
493 tm.year = msToYear(ms) - 1900;
494 tm.isDST = dstOff != 0.0;
495
496 tm.utcOffset = static_cast<long>((dstOff + getUTCOffset()) / msPerSecond);
497 tm.timeZone = NULL;
498}
499
500} // namespace KJS
Note: See TracBrowser for help on using the repository browser.