source: webkit/trunk/JavaScriptCore/runtime/DateMath.cpp@ 38528

Last change on this file since 38528 was 38176, checked in by Simon Hausmann, 17 years ago

2008-11-06 Laszlo Gombos <Laszlo Gombos>

Reviewed by Simon Hausmann.

Include strings.h for strncasecmp().
This is needed for compilation inside Symbian and it is also
confirmed by the man-page on Linux.

  • Property svn:eol-style set to native
File size: 31.2 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 "JSNumberCell.h"
46#include <math.h>
47#include <stdint.h>
48#include <time.h>
49#include <wtf/ASCIICType.h>
50#include <wtf/Assertions.h>
51#include <wtf/MathExtras.h>
52#include <wtf/StringExtras.h>
53
54#if HAVE(ERRNO_H)
55#include <errno.h>
56#endif
57
58#if PLATFORM(DARWIN)
59#include <notify.h>
60#endif
61
62#if HAVE(SYS_TIME_H)
63#include <sys/time.h>
64#endif
65
66#if HAVE(SYS_TIMEB_H)
67#include <sys/timeb.h>
68#endif
69
70#if HAVE(STRINGS_H)
71#include <strings.h>
72#endif
73
74using namespace WTF;
75
76namespace JSC {
77
78/* Constants */
79
80static const double minutesPerDay = 24.0 * 60.0;
81static const double secondsPerDay = 24.0 * 60.0 * 60.0;
82static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
83
84static const double usecPerSec = 1000000.0;
85
86static const double maxUnixTime = 2145859200.0; // 12/31/2037
87
88// Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
89// First for non-leap years, then for leap years.
90static const int firstDayOfMonth[2][12] = {
91 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
92 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
93};
94
95static inline bool isLeapYear(int year)
96{
97 if (year % 4 != 0)
98 return false;
99 if (year % 400 == 0)
100 return true;
101 if (year % 100 == 0)
102 return false;
103 return true;
104}
105
106static inline int daysInYear(int year)
107{
108 return 365 + isLeapYear(year);
109}
110
111static inline double daysFrom1970ToYear(int year)
112{
113 // The Gregorian Calendar rules for leap years:
114 // Every fourth year is a leap year. 2004, 2008, and 2012 are leap years.
115 // However, every hundredth year is not a leap year. 1900 and 2100 are not leap years.
116 // Every four hundred years, there's a leap year after all. 2000 and 2400 are leap years.
117
118 static const int leapDaysBefore1971By4Rule = 1970 / 4;
119 static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
120 static const int leapDaysBefore1971By400Rule = 1970 / 400;
121
122 const double yearMinusOne = year - 1;
123 const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
124 const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
125 const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
126
127 return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
128}
129
130static inline double msToDays(double ms)
131{
132 return floor(ms / msPerDay);
133}
134
135static inline int msToYear(double ms)
136{
137 int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
138 double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
139 if (msFromApproxYearTo1970 > ms)
140 return approxYear - 1;
141 if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
142 return approxYear + 1;
143 return approxYear;
144}
145
146static inline int dayInYear(double ms, int year)
147{
148 return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
149}
150
151static inline double msToMilliseconds(double ms)
152{
153 double result = fmod(ms, msPerDay);
154 if (result < 0)
155 result += msPerDay;
156 return result;
157}
158
159// 0: Sunday, 1: Monday, etc.
160static inline int msToWeekDay(double ms)
161{
162 int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
163 if (wd < 0)
164 wd += 7;
165 return wd;
166}
167
168static inline int msToSeconds(double ms)
169{
170 double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
171 if (result < 0)
172 result += secondsPerMinute;
173 return static_cast<int>(result);
174}
175
176static inline int msToMinutes(double ms)
177{
178 double result = fmod(floor(ms / msPerMinute), minutesPerHour);
179 if (result < 0)
180 result += minutesPerHour;
181 return static_cast<int>(result);
182}
183
184static inline int msToHours(double ms)
185{
186 double result = fmod(floor(ms/msPerHour), hoursPerDay);
187 if (result < 0)
188 result += hoursPerDay;
189 return static_cast<int>(result);
190}
191
192static inline int monthFromDayInYear(int dayInYear, bool leapYear)
193{
194 const int d = dayInYear;
195 int step;
196
197 if (d < (step = 31))
198 return 0;
199 step += (leapYear ? 29 : 28);
200 if (d < step)
201 return 1;
202 if (d < (step += 31))
203 return 2;
204 if (d < (step += 30))
205 return 3;
206 if (d < (step += 31))
207 return 4;
208 if (d < (step += 30))
209 return 5;
210 if (d < (step += 31))
211 return 6;
212 if (d < (step += 31))
213 return 7;
214 if (d < (step += 30))
215 return 8;
216 if (d < (step += 31))
217 return 9;
218 if (d < (step += 30))
219 return 10;
220 return 11;
221}
222
223static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
224{
225 startDayOfThisMonth = startDayOfNextMonth;
226 startDayOfNextMonth += daysInThisMonth;
227 return (dayInYear <= startDayOfNextMonth);
228}
229
230static inline int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
231{
232 const int d = dayInYear;
233 int step;
234 int next = 30;
235
236 if (d <= next)
237 return d + 1;
238 const int daysInFeb = (leapYear ? 29 : 28);
239 if (checkMonth(d, step, next, daysInFeb))
240 return d - step;
241 if (checkMonth(d, step, next, 31))
242 return d - step;
243 if (checkMonth(d, step, next, 30))
244 return d - step;
245 if (checkMonth(d, step, next, 31))
246 return d - step;
247 if (checkMonth(d, step, next, 30))
248 return d - step;
249 if (checkMonth(d, step, next, 31))
250 return d - step;
251 if (checkMonth(d, step, next, 31))
252 return d - step;
253 if (checkMonth(d, step, next, 30))
254 return d - step;
255 if (checkMonth(d, step, next, 31))
256 return d - step;
257 if (checkMonth(d, step, next, 30))
258 return d - step;
259 step = next;
260 return d - step;
261}
262
263static inline int monthToDayInYear(int month, bool isLeapYear)
264{
265 return firstDayOfMonth[isLeapYear][month];
266}
267
268static inline double timeToMS(double hour, double min, double sec, double ms)
269{
270 return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
271}
272
273static int dateToDayInYear(int year, int month, int day)
274{
275 year += month / 12;
276
277 month %= 12;
278 if (month < 0) {
279 month += 12;
280 --year;
281 }
282
283 int yearday = static_cast<int>(floor(daysFrom1970ToYear(year)));
284 int monthday = monthToDayInYear(month, isLeapYear(year));
285
286 return yearday + monthday + day - 1;
287}
288
289double getCurrentUTCTime()
290{
291 return floor(getCurrentUTCTimeWithMicroseconds());
292}
293
294#if PLATFORM(WIN_OS)
295
296static LARGE_INTEGER qpcFrequency;
297static bool syncedTime;
298
299static double highResUpTime()
300{
301 // We use QPC, but only after sanity checking its result, due to bugs:
302 // http://support.microsoft.com/kb/274323
303 // http://support.microsoft.com/kb/895980
304 // http://msdn.microsoft.com/en-us/library/ms644904.aspx ("...you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL)."
305
306 static LARGE_INTEGER qpcLast;
307 static DWORD tickCountLast;
308 static bool inited;
309
310 LARGE_INTEGER qpc;
311 QueryPerformanceCounter(&qpc);
312 DWORD tickCount = GetTickCount();
313
314 if (inited) {
315 __int64 qpcElapsed = ((qpc.QuadPart - qpcLast.QuadPart) * 1000) / qpcFrequency.QuadPart;
316 __int64 tickCountElapsed;
317 if (tickCount >= tickCountLast)
318 tickCountElapsed = (tickCount - tickCountLast);
319 else {
320#if COMPILER(MINGW)
321 __int64 tickCountLarge = tickCount + 0x100000000ULL;
322#else
323 __int64 tickCountLarge = tickCount + 0x100000000I64;
324#endif
325 tickCountElapsed = tickCountLarge - tickCountLast;
326 }
327
328 // force a re-sync if QueryPerformanceCounter differs from GetTickCount by more than 500ms.
329 // (500ms value is from http://support.microsoft.com/kb/274323)
330 __int64 diff = tickCountElapsed - qpcElapsed;
331 if (diff > 500 || diff < -500)
332 syncedTime = false;
333 } else
334 inited = true;
335
336 qpcLast = qpc;
337 tickCountLast = tickCount;
338
339 return (1000.0 * qpc.QuadPart) / static_cast<double>(qpcFrequency.QuadPart);;
340}
341
342static double lowResUTCTime()
343{
344 struct _timeb timebuffer;
345 _ftime(&timebuffer);
346 return timebuffer.time * msPerSecond + timebuffer.millitm;
347}
348
349static bool qpcAvailable()
350{
351 static bool available;
352 static bool checked;
353
354 if (checked)
355 return available;
356
357 available = QueryPerformanceFrequency(&qpcFrequency);
358 checked = true;
359 return available;
360}
361
362#endif
363
364double getCurrentUTCTimeWithMicroseconds()
365{
366#if PLATFORM(WIN_OS)
367 // Use a combination of ftime and QueryPerformanceCounter.
368 // ftime returns the information we want, but doesn't have sufficient resolution.
369 // QueryPerformanceCounter has high resolution, but is only usable to measure time intervals.
370 // To combine them, we call ftime and QueryPerformanceCounter initially. Later calls will use QueryPerformanceCounter
371 // by itself, adding the delta to the saved ftime. We periodically re-sync to correct for drift.
372 static bool started;
373 static double syncLowResUTCTime;
374 static double syncHighResUpTime;
375 static double lastUTCTime;
376
377 double lowResTime = lowResUTCTime();
378
379 if (!qpcAvailable())
380 return lowResTime;
381
382 double highResTime = highResUpTime();
383
384 if (!syncedTime) {
385 timeBeginPeriod(1); // increase time resolution around low-res time getter
386 syncLowResUTCTime = lowResTime = lowResUTCTime();
387 timeEndPeriod(1); // restore time resolution
388 syncHighResUpTime = highResTime;
389 syncedTime = true;
390 }
391
392 double highResElapsed = highResTime - syncHighResUpTime;
393 double utc = syncLowResUTCTime + highResElapsed;
394
395 // force a clock re-sync if we've drifted
396 double lowResElapsed = lowResTime - syncLowResUTCTime;
397 const double maximumAllowedDriftMsec = 15.625 * 2.0; // 2x the typical low-res accuracy
398 if (fabs(highResElapsed - lowResElapsed) > maximumAllowedDriftMsec)
399 syncedTime = false;
400
401 // make sure time doesn't run backwards (only correct if difference is < 2 seconds, since DST or clock changes could occur)
402 const double backwardTimeLimit = 2000.0;
403 if (utc < lastUTCTime && (lastUTCTime - utc) < backwardTimeLimit)
404 return lastUTCTime;
405 lastUTCTime = utc;
406#else
407 struct timeval tv;
408 gettimeofday(&tv, 0);
409 double utc = tv.tv_sec * msPerSecond + tv.tv_usec / 1000.0;
410#endif
411 return utc;
412}
413
414void getLocalTime(const time_t* localTime, struct tm* localTM)
415{
416#if COMPILER(MSVC7) || COMPILER(MINGW)
417 *localTM = *localtime(localTime);
418#elif COMPILER(MSVC)
419 localtime_s(localTM, localTime);
420#else
421 localtime_r(localTime, localTM);
422#endif
423}
424
425// There is a hard limit at 2038 that we currently do not have a workaround
426// for (rdar://problem/5052975).
427static inline int maximumYearForDST()
428{
429 return 2037;
430}
431
432static inline int minimumYearForDST()
433{
434 // Because of the 2038 issue (see maximumYearForDST) if the current year is
435 // greater than the max year minus 27 (2010), we want to use the max year
436 // minus 27 instead, to ensure there is a range of 28 years that all years
437 // can map to.
438 return std::min(msToYear(getCurrentUTCTime()), maximumYearForDST() - 27) ;
439}
440
441/*
442 * Find an equivalent year for the one given, where equivalence is deterined by
443 * the two years having the same leapness and the first day of the year, falling
444 * on the same day of the week.
445 *
446 * This function returns a year between this current year and 2037, however this
447 * function will potentially return incorrect results if the current year is after
448 * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
449 * 2100, (rdar://problem/5055038).
450 */
451int equivalentYearForDST(int year)
452{
453 // It is ok if the cached year is not the current year as long as the rules
454 // for DST did not change between the two years; if they did the app would need
455 // to be restarted.
456 static int minYear = minimumYearForDST();
457 int maxYear = maximumYearForDST();
458
459 int difference;
460 if (year > maxYear)
461 difference = minYear - year;
462 else if (year < minYear)
463 difference = maxYear - year;
464 else
465 return year;
466
467 int quotient = difference / 28;
468 int product = (quotient) * 28;
469
470 year += product;
471 ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
472 return year;
473}
474
475static int32_t calculateUTCOffset()
476{
477 tm localt;
478 memset(&localt, 0, sizeof(localt));
479
480 // get the difference between this time zone and UTC on Jan 01, 2000 12:00:00 AM
481 localt.tm_mday = 1;
482 localt.tm_year = 100;
483 time_t utcOffset = 946684800 - mktime(&localt);
484
485 return static_cast<int32_t>(utcOffset * 1000);
486}
487
488#if PLATFORM(DARWIN)
489static 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.
490static bool s_haveCachedUTCOffset;
491static int s_notificationToken;
492#endif
493
494/*
495 * Get the difference in milliseconds between this time zone and UTC (GMT)
496 * NOT including DST.
497 */
498double getUTCOffset()
499{
500#if PLATFORM(DARWIN)
501 if (s_haveCachedUTCOffset) {
502 int notified;
503 uint32_t status = notify_check(s_notificationToken, &notified);
504 if (status == NOTIFY_STATUS_OK && !notified)
505 return s_cachedUTCOffset;
506 }
507#endif
508
509 int32_t utcOffset = calculateUTCOffset();
510
511#if PLATFORM(DARWIN)
512 // Theoretically, it is possible that several threads will be executing this code at once, in which case we will have a race condition,
513 // and a newer value may be overwritten. In practice, time zones don't change that often.
514 s_cachedUTCOffset = utcOffset;
515#endif
516
517 return utcOffset;
518}
519
520/*
521 * Get the DST offset for the time passed in. Takes
522 * seconds (not milliseconds) and cannot handle dates before 1970
523 * on some OS'
524 */
525static double getDSTOffsetSimple(double localTimeSeconds, double utcOffset)
526{
527 if (localTimeSeconds > maxUnixTime)
528 localTimeSeconds = maxUnixTime;
529 else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
530 localTimeSeconds += secondsPerDay;
531
532 //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
533 double offsetTime = (localTimeSeconds * msPerSecond) + utcOffset;
534
535 // Offset from UTC but doesn't include DST obviously
536 int offsetHour = msToHours(offsetTime);
537 int offsetMinute = msToMinutes(offsetTime);
538
539 // FIXME: time_t has a potential problem in 2038
540 time_t localTime = static_cast<time_t>(localTimeSeconds);
541
542 tm localTM;
543 getLocalTime(&localTime, &localTM);
544
545 double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
546
547 if (diff < 0)
548 diff += secondsPerDay;
549
550 return (diff * msPerSecond);
551}
552
553// Get the DST offset, given a time in UTC
554static double getDSTOffset(double ms, double utcOffset)
555{
556 // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
557 // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
558 // standard explicitly dictates that historical information should not be considered when
559 // determining DST. For this reason we shift away from years that localtime can handle but would
560 // return historically accurate information.
561 int year = msToYear(ms);
562 int equivalentYear = equivalentYearForDST(year);
563 if (year != equivalentYear) {
564 bool leapYear = isLeapYear(year);
565 int dayInYearLocal = dayInYear(ms, year);
566 int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
567 int month = monthFromDayInYear(dayInYearLocal, leapYear);
568 int day = dateToDayInYear(equivalentYear, month, dayInMonth);
569 ms = (day * msPerDay) + msToMilliseconds(ms);
570 }
571
572 return getDSTOffsetSimple(ms / msPerSecond, utcOffset);
573}
574
575double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
576{
577 int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
578 double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
579 double result = (day * msPerDay) + ms;
580
581 if (!inputIsUTC) { // convert to UTC
582 double utcOffset = getUTCOffset();
583 result -= utcOffset;
584 result -= getDSTOffset(result, utcOffset);
585 }
586
587 return result;
588}
589
590void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
591{
592 // input is UTC
593 double dstOff = 0.0;
594 const double utcOff = getUTCOffset();
595
596 if (!outputIsUTC) { // convert to local time
597 dstOff = getDSTOffset(ms, utcOff);
598 ms += dstOff + utcOff;
599 }
600
601 const int year = msToYear(ms);
602 tm.second = msToSeconds(ms);
603 tm.minute = msToMinutes(ms);
604 tm.hour = msToHours(ms);
605 tm.weekDay = msToWeekDay(ms);
606 tm.yearDay = dayInYear(ms, year);
607 tm.monthDay = dayInMonthFromDayInYear(tm.yearDay, isLeapYear(year));
608 tm.month = monthFromDayInYear(tm.yearDay, isLeapYear(year));
609 tm.year = year - 1900;
610 tm.isDST = dstOff != 0.0;
611
612 tm.utcOffset = static_cast<long>((dstOff + utcOff) / msPerSecond);
613 tm.timeZone = NULL;
614}
615
616void initDateMath()
617{
618#ifndef NDEBUG
619 static bool alreadyInitialized;
620 ASSERT(!alreadyInitialized++);
621#endif
622
623 equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
624#if PLATFORM(DARWIN)
625 // Register for a notification whenever the time zone changes.
626 uint32_t status = notify_register_check("com.apple.system.timezone", &s_notificationToken);
627 if (status == NOTIFY_STATUS_OK) {
628 s_cachedUTCOffset = calculateUTCOffset();
629 s_haveCachedUTCOffset = true;
630 }
631#endif
632}
633
634static inline double ymdhmsToSeconds(long year, int mon, int day, int hour, int minute, int second)
635{
636 double days = (day - 32075)
637 + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
638 + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
639 - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
640 - 2440588;
641 return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
642}
643
644// We follow the recommendation of RFC 2822 to consider all
645// obsolete time zones not listed here equivalent to "-0000".
646static const struct KnownZone {
647#if !PLATFORM(WIN_OS)
648 const
649#endif
650 char tzName[4];
651 int tzOffset;
652} known_zones[] = {
653 { "UT", 0 },
654 { "GMT", 0 },
655 { "EST", -300 },
656 { "EDT", -240 },
657 { "CST", -360 },
658 { "CDT", -300 },
659 { "MST", -420 },
660 { "MDT", -360 },
661 { "PST", -480 },
662 { "PDT", -420 }
663};
664
665inline static void skipSpacesAndComments(const char*& s)
666{
667 int nesting = 0;
668 char ch;
669 while ((ch = *s)) {
670 if (!isASCIISpace(ch)) {
671 if (ch == '(')
672 nesting++;
673 else if (ch == ')' && nesting > 0)
674 nesting--;
675 else if (nesting == 0)
676 break;
677 }
678 s++;
679 }
680}
681
682// returns 0-11 (Jan-Dec); -1 on failure
683static int findMonth(const char* monthStr)
684{
685 ASSERT(monthStr);
686 char needle[4];
687 for (int i = 0; i < 3; ++i) {
688 if (!*monthStr)
689 return -1;
690 needle[i] = static_cast<char>(toASCIILower(*monthStr++));
691 }
692 needle[3] = '\0';
693 const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
694 const char *str = strstr(haystack, needle);
695 if (str) {
696 int position = static_cast<int>(str - haystack);
697 if (position % 3 == 0)
698 return position / 3;
699 }
700 return -1;
701}
702
703double parseDate(const UString &date)
704{
705 // This parses a date in the form:
706 // Tuesday, 09-Nov-99 23:12:40 GMT
707 // or
708 // Sat, 01-Jan-2000 08:00:00 GMT
709 // or
710 // Sat, 01 Jan 2000 08:00:00 GMT
711 // or
712 // 01 Jan 99 22:00 +0100 (exceptions in rfc822/rfc2822)
713 // ### non RFC formats, added for Javascript:
714 // [Wednesday] January 09 1999 23:12:40 GMT
715 // [Wednesday] January 09 23:12:40 GMT 1999
716 //
717 // We ignore the weekday.
718
719 CString dateCString = date.UTF8String();
720 const char *dateString = dateCString.c_str();
721
722 // Skip leading space
723 skipSpacesAndComments(dateString);
724
725 long month = -1;
726 const char *wordStart = dateString;
727 // Check contents of first words if not number
728 while (*dateString && !isASCIIDigit(*dateString)) {
729 if (isASCIISpace(*dateString) || *dateString == '(') {
730 if (dateString - wordStart >= 3)
731 month = findMonth(wordStart);
732 skipSpacesAndComments(dateString);
733 wordStart = dateString;
734 } else
735 dateString++;
736 }
737
738 // Missing delimiter between month and day (like "January29")?
739 if (month == -1 && wordStart != dateString)
740 month = findMonth(wordStart);
741
742 skipSpacesAndComments(dateString);
743
744 if (!*dateString)
745 return NaN;
746
747 // ' 09-Nov-99 23:12:40 GMT'
748 char *newPosStr;
749 errno = 0;
750 long day = strtol(dateString, &newPosStr, 10);
751 if (errno)
752 return NaN;
753 dateString = newPosStr;
754
755 if (!*dateString)
756 return NaN;
757
758 if (day < 0)
759 return NaN;
760
761 long year = 0;
762 if (day > 31) {
763 // ### where is the boundary and what happens below?
764 if (*dateString != '/')
765 return NaN;
766 // looks like a YYYY/MM/DD date
767 if (!*++dateString)
768 return NaN;
769 year = day;
770 month = strtol(dateString, &newPosStr, 10) - 1;
771 if (errno)
772 return NaN;
773 dateString = newPosStr;
774 if (*dateString++ != '/' || !*dateString)
775 return NaN;
776 day = strtol(dateString, &newPosStr, 10);
777 if (errno)
778 return NaN;
779 dateString = newPosStr;
780 } else if (*dateString == '/' && month == -1) {
781 dateString++;
782 // This looks like a MM/DD/YYYY date, not an RFC date.
783 month = day - 1; // 0-based
784 day = strtol(dateString, &newPosStr, 10);
785 if (errno)
786 return NaN;
787 if (day < 1 || day > 31)
788 return NaN;
789 dateString = newPosStr;
790 if (*dateString == '/')
791 dateString++;
792 if (!*dateString)
793 return NaN;
794 } else {
795 if (*dateString == '-')
796 dateString++;
797
798 skipSpacesAndComments(dateString);
799
800 if (*dateString == ',')
801 dateString++;
802
803 if (month == -1) { // not found yet
804 month = findMonth(dateString);
805 if (month == -1)
806 return NaN;
807
808 while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
809 dateString++;
810
811 if (!*dateString)
812 return NaN;
813
814 // '-99 23:12:40 GMT'
815 if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
816 return NaN;
817 dateString++;
818 }
819 }
820
821 if (month < 0 || month > 11)
822 return NaN;
823
824 // '99 23:12:40 GMT'
825 if (year <= 0 && *dateString) {
826 year = strtol(dateString, &newPosStr, 10);
827 if (errno)
828 return NaN;
829 }
830
831 // Don't fail if the time is missing.
832 long hour = 0;
833 long minute = 0;
834 long second = 0;
835 if (!*newPosStr)
836 dateString = newPosStr;
837 else {
838 // ' 23:12:40 GMT'
839 if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
840 if (*newPosStr != ':')
841 return NaN;
842 // There was no year; the number was the hour.
843 year = -1;
844 } else {
845 // in the normal case (we parsed the year), advance to the next number
846 dateString = ++newPosStr;
847 skipSpacesAndComments(dateString);
848 }
849
850 hour = strtol(dateString, &newPosStr, 10);
851 // Do not check for errno here since we want to continue
852 // even if errno was set becasue we are still looking
853 // for the timezone!
854
855 // Read a number? If not, this might be a timezone name.
856 if (newPosStr != dateString) {
857 dateString = newPosStr;
858
859 if (hour < 0 || hour > 23)
860 return NaN;
861
862 if (!*dateString)
863 return NaN;
864
865 // ':12:40 GMT'
866 if (*dateString++ != ':')
867 return NaN;
868
869 minute = strtol(dateString, &newPosStr, 10);
870 if (errno)
871 return NaN;
872 dateString = newPosStr;
873
874 if (minute < 0 || minute > 59)
875 return NaN;
876
877 // ':40 GMT'
878 if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
879 return NaN;
880
881 // seconds are optional in rfc822 + rfc2822
882 if (*dateString ==':') {
883 dateString++;
884
885 second = strtol(dateString, &newPosStr, 10);
886 if (errno)
887 return NaN;
888 dateString = newPosStr;
889
890 if (second < 0 || second > 59)
891 return NaN;
892 }
893
894 skipSpacesAndComments(dateString);
895
896 if (strncasecmp(dateString, "AM", 2) == 0) {
897 if (hour > 12)
898 return NaN;
899 if (hour == 12)
900 hour = 0;
901 dateString += 2;
902 skipSpacesAndComments(dateString);
903 } else if (strncasecmp(dateString, "PM", 2) == 0) {
904 if (hour > 12)
905 return NaN;
906 if (hour != 12)
907 hour += 12;
908 dateString += 2;
909 skipSpacesAndComments(dateString);
910 }
911 }
912 }
913
914 bool haveTZ = false;
915 int offset = 0;
916
917 // Don't fail if the time zone is missing.
918 // Some websites omit the time zone (4275206).
919 if (*dateString) {
920 if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
921 dateString += 3;
922 haveTZ = true;
923 }
924
925 if (*dateString == '+' || *dateString == '-') {
926 long o = strtol(dateString, &newPosStr, 10);
927 if (errno)
928 return NaN;
929 dateString = newPosStr;
930
931 if (o < -9959 || o > 9959)
932 return NaN;
933
934 int sgn = (o < 0) ? -1 : 1;
935 o = abs(o);
936 if (*dateString != ':') {
937 offset = ((o / 100) * 60 + (o % 100)) * sgn;
938 } else { // GMT+05:00
939 long o2 = strtol(dateString, &newPosStr, 10);
940 if (errno)
941 return NaN;
942 dateString = newPosStr;
943 offset = (o * 60 + o2) * sgn;
944 }
945 haveTZ = true;
946 } else {
947 for (int i = 0; i < int(sizeof(known_zones) / sizeof(KnownZone)); i++) {
948 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
949 offset = known_zones[i].tzOffset;
950 dateString += strlen(known_zones[i].tzName);
951 haveTZ = true;
952 break;
953 }
954 }
955 }
956 }
957
958 skipSpacesAndComments(dateString);
959
960 if (*dateString && year == -1) {
961 year = strtol(dateString, &newPosStr, 10);
962 if (errno)
963 return NaN;
964 dateString = newPosStr;
965 }
966
967 skipSpacesAndComments(dateString);
968
969 // Trailing garbage
970 if (*dateString)
971 return NaN;
972
973 // Y2K: Handle 2 digit years.
974 if (year >= 0 && year < 100) {
975 if (year < 50)
976 year += 2000;
977 else
978 year += 1900;
979 }
980
981 // fall back to local timezone
982 if (!haveTZ) {
983 GregorianDateTime t;
984 t.monthDay = day;
985 t.month = month;
986 t.year = year - 1900;
987 t.isDST = -1;
988 t.second = second;
989 t.minute = minute;
990 t.hour = hour;
991
992 // Use our gregorianDateTimeToMS() rather than mktime() as the latter can't handle the full year range.
993 return gregorianDateTimeToMS(t, 0, false);
994 }
995
996 return (ymdhmsToSeconds(year, month + 1, day, hour, minute, second) - (offset * 60.0)) * msPerSecond;
997}
998
999double timeClip(double t)
1000{
1001 if (!isfinite(t))
1002 return NaN;
1003 if (fabs(t) > 8.64E15)
1004 return NaN;
1005 return trunc(t);
1006}
1007
1008UString formatDate(const GregorianDateTime &t)
1009{
1010 char buffer[100];
1011 snprintf(buffer, sizeof(buffer), "%s %s %02d %04d",
1012 weekdayName[(t.weekDay + 6) % 7],
1013 monthName[t.month], t.monthDay, t.year + 1900);
1014 return buffer;
1015}
1016
1017UString formatDateUTCVariant(const GregorianDateTime &t)
1018{
1019 char buffer[100];
1020 snprintf(buffer, sizeof(buffer), "%s, %02d %s %04d",
1021 weekdayName[(t.weekDay + 6) % 7],
1022 t.monthDay, monthName[t.month], t.year + 1900);
1023 return buffer;
1024}
1025
1026UString formatTime(const GregorianDateTime &t, bool utc)
1027{
1028 char buffer[100];
1029 if (utc) {
1030 snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT", t.hour, t.minute, t.second);
1031 } else {
1032 int offset = abs(gmtoffset(t));
1033 char tzname[70];
1034 struct tm gtm = t;
1035 strftime(tzname, sizeof(tzname), "%Z", &gtm);
1036
1037 if (tzname[0]) {
1038 snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d (%s)",
1039 t.hour, t.minute, t.second,
1040 gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60, tzname);
1041 } else {
1042 snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d",
1043 t.hour, t.minute, t.second,
1044 gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60);
1045 }
1046 }
1047 return UString(buffer);
1048}
1049
1050} // namespace JSC
Note: See TracBrowser for help on using the repository browser.