root/trunk/JavaScriptCore/kjs/DateMath.cpp

Revision 370, 28.0 kB (checked in by mbensi, 2 years ago)

merge with webkit revision 34956

Line 
1 /*
2  * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
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 using namespace WTF;
71
72 namespace KJS {
73
74 /* Constants */
75
76 static const double minutesPerDay = 24.0 * 60.0;
77 static const double secondsPerDay = 24.0 * 60.0 * 60.0;
78 static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
79
80 static const double usecPerSec = 1000000.0;
81
82 static const double maxUnixTime = 2145859200.0; // 12/31/2037
83
84 // Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
85 // First for non-leap years, then for leap years.
86 static const int firstDayOfMonth[2][12] = {
87     {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
88     {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
89 };
90
91 static inline bool isLeapYear(int year)
92 {
93     if (year % 4 != 0)
94         return false;
95     if (year % 400 == 0)
96         return true;
97     if (year % 100 == 0)
98         return false;
99     return true;
100 }
101
102 static inline int daysInYear(int year)
103 {
104     return 365 + isLeapYear(year);
105 }
106
107 static inline double daysFrom1970ToYear(int year)
108 {
109     // The Gregorian Calendar rules for leap years:
110     // Every fourth year is a leap year.  2004, 2008, and 2012 are leap years.
111     // However, every hundredth year is not a leap year.  1900 and 2100 are not leap years.
112     // Every four hundred years, there's a leap year after all.  2000 and 2400 are leap years.
113
114     static const int leapDaysBefore1971By4Rule = 1970 / 4;
115     static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
116     static const int leapDaysBefore1971By400Rule = 1970 / 400;
117
118     const double yearMinusOne = year - 1;
119     const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
120     const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
121     const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
122
123     return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
124 }
125
126 static inline double msToDays(double ms)
127 {
128     return floor(ms / msPerDay);
129 }
130
131 static inline int msToYear(double ms)
132 {
133     int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
134     double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
135     if (msFromApproxYearTo1970 > ms)
136         return approxYear - 1;
137     if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
138         return approxYear + 1;
139     return approxYear;
140 }
141
142 static inline int dayInYear(double ms, int year)
143 {
144     return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
145 }
146
147 static inline double msToMilliseconds(double ms)
148 {
149     double result = fmod(ms, msPerDay);
150     if (result < 0)
151         result += msPerDay;
152     return result;
153 }
154
155 // 0: Sunday, 1: Monday, etc.
156 static inline int msToWeekDay(double ms)
157 {
158     int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
159     if (wd < 0)
160         wd += 7;
161     return wd;
162 }
163
164 static inline int msToSeconds(double ms)
165 {
166     double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
167     if (result < 0)
168         result += secondsPerMinute;
169     return static_cast<int>(result);
170 }
171
172 static inline int msToMinutes(double ms)
173 {
174     double result = fmod(floor(ms / msPerMinute), minutesPerHour);
175     if (result < 0)
176         result += minutesPerHour;
177     return static_cast<int>(result);
178 }
179
180 static inline int msToHours(double ms)
181 {
182     double result = fmod(floor(ms/msPerHour), hoursPerDay);
183     if (result < 0)
184         result += hoursPerDay;
185     return static_cast<int>(result);
186 }
187
188 static inline int monthFromDayInYear(int dayInYear, bool leapYear)
189 {
190     const int d = dayInYear;
191     int step;
192
193     if (d < (step = 31))
194         return 0;
195     step += (leapYear ? 29 : 28);
196     if (d < step)
197         return 1;
198     if (d < (step += 31))
199         return 2;
200     if (d < (step += 30))
201         return 3;
202     if (d < (step += 31))
203         return 4;
204     if (d < (step += 30))
205         return 5;
206     if (d < (step += 31))
207         return 6;
208     if (d < (step += 31))
209         return 7;
210     if (d < (step += 30))
211         return 8;
212     if (d < (step += 31))
213         return 9;
214     if (d < (step += 30))
215         return 10;
216     return 11;
217 }
218
219 static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
220 {
221     startDayOfThisMonth = startDayOfNextMonth;
222     startDayOfNextMonth += daysInThisMonth;
223     return (dayInYear <= startDayOfNextMonth);
224 }
225
226 static inline int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
227 {
228     const int d = dayInYear;
229     int step;
230     int next = 30;
231
232     if (d <= next)
233         return d + 1;
234     const int daysInFeb = (leapYear ? 29 : 28);
235     if (checkMonth(d, step, next, daysInFeb))
236         return d - step;
237     if (checkMonth(d, step, next, 31))
238         return d - step;
239     if (checkMonth(d, step, next, 30))
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, 31))
248         return d - step;
249     if (checkMonth(d, step, next, 30))
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     step = next;
256     return d - step;
257 }
258
259 static inline int monthToDayInYear(int month, bool isLeapYear)
260 {
261     return firstDayOfMonth[isLeapYear][month];
262 }
263
264 static inline double timeToMS(double hour, double min, double sec, double ms)
265 {
266     return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
267 }
268
269 static int dateToDayInYear(int year, int month, int day)
270 {
271     year += month / 12;
272
273     month %= 12;
274     if (month < 0) {
275         month += 12;
276         --year;
277     }
278
279     int yearday = static_cast<int>(floor(daysFrom1970ToYear(year)));
280     int monthday = monthToDayInYear(month, isLeapYear(year));
281
282     return yearday + monthday + day - 1;
283 }
284
285 double getCurrentUTCTime()
286 {
287     return floor(getCurrentUTCTimeWithMicroseconds());
288 }
289
290 double getCurrentUTCTimeWithMicroseconds()
291 {
292 #if PLATFORM(WIN_OS)
293     // FIXME: the implementation for Windows is only millisecond resolution.
294 #if COMPILER(BORLAND)
295     struct timeb timebuffer;
296     ftime(&timebuffer);
297 #else
298     struct _timeb timebuffer;
299     _ftime(&timebuffer);
300 #endif
301     double utc = timebuffer.time * msPerSecond + timebuffer.millitm;
302 #else
303     struct timeval tv;
304     gettimeofday(&tv, 0);
305     double utc = tv.tv_sec * msPerSecond + tv.tv_usec / 1000.0;
306 #endif
307     return utc;
308 }
309
310 void getLocalTime(const time_t* localTime, struct tm* localTM)
311 {
312 #if PLATFORM(QT)
313 #if USE(MULTIPLE_THREADS)
314 #error Mulitple threads are currently not supported in the Qt/mingw build
315 #endif
316     *localTM = *localtime(localTime);
317 #elif PLATFORM(WIN_OS)
318     #if COMPILER(MSVC7)
319     *localTM = *localtime(localTime);
320     #else
321     localtime_s(localTM, localTime);
322     #endif
323 #else
324     localtime_r(localTime, localTM);
325 #endif
326 }
327
328 // There is a hard limit at 2038 that we currently do not have a workaround
329 // for (rdar://problem/5052975).
330 static inline int maximumYearForDST()
331 {
332     return 2037;
333 }
334
335 static inline int mimimumYearForDST()
336 {
337     // Because of the 2038 issue (see maximumYearForDST) if the current year is
338     // greater than the max year minus 27 (2010), we want to use the max year
339     // minus 27 instead, to ensure there is a range of 28 years that all years
340     // can map to.
341     return std::min(msToYear(getCurrentUTCTime()), maximumYearForDST() - 27) ;
342 }
343
344 /*
345  * Find an equivalent year for the one given, where equivalence is deterined by
346  * the two years having the same leapness and the first day of the year, falling
347  * on the same day of the week.
348  *
349  * This function returns a year between this current year and 2037, however this
350  * function will potentially return incorrect results if the current year is after
351  * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
352  * 2100, (rdar://problem/5055038).
353  */
354 int equivalentYearForDST(int year)
355 {
356     // It is ok if the cached year is not the current year as long as the rules
357     // for DST did not change between the two years; if they did the app would need
358     // to be restarted.
359     static int minYear = mimimumYearForDST();
360     int maxYear = maximumYearForDST();
361
362     int difference;
363     if (year > maxYear)
364         difference = minYear - year;
365     else if (year < minYear)
366         difference = maxYear - year;
367     else
368         return year;
369
370     int quotient = difference / 28;
371     int product = (quotient) * 28;
372
373     year += product;
374     ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
375     return year;
376 }
377
378 static int32_t calculateUTCOffset()
379 {
380     tm localt;
381     memset(&localt, 0, sizeof(localt));
382  
383     // get the difference between this time zone and UTC on Jan 01, 2000 12:00:00 AM
384     localt.tm_mday = 1;
385     localt.tm_year = 100;
386     time_t utcOffset = 946684800 - mktime(&localt);
387
388     return static_cast<int32_t>(utcOffset * 1000);
389 }
390
391 #if PLATFORM(DARWIN)
392 static 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.
393 static bool s_haveCachedUTCOffset;
394 static int s_notificationToken;
395 #endif
396
397 /*
398  * Get the difference in milliseconds between this time zone and UTC (GMT)
399  * NOT including DST.
400  */
401 double getUTCOffset()
402 {
403 #if PLATFORM(DARWIN)
404     if (s_haveCachedUTCOffset) {
405         int notified;
406         uint32_t status = notify_check(s_notificationToken, &notified);
407         if (status == NOTIFY_STATUS_OK && !notified)
408             return s_cachedUTCOffset;
409     }
410 #endif
411
412     int32_t utcOffset = calculateUTCOffset();
413
414 #if PLATFORM(DARWIN)
415     // 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;
418 #endif
419
420     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  */
428 static double getDSTOffsetSimple(double localTimeSeconds, double utcOffset)
429 {
430     if (localTimeSeconds > maxUnixTime)
431         localTimeSeconds = maxUnixTime;
432     else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0)
433         localTimeSeconds += secondsPerDay;
434
435     //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
436     double offsetTime = (localTimeSeconds * msPerSecond) + utcOffset;
437
438     // Offset from UTC but doesn't include DST obviously
439     int offsetHour =  msToHours(offsetTime);
440     int offsetMinute =  msToMinutes(offsetTime);
441
442     // FIXME: time_t has a potential problem in 2038
443     time_t localTime = static_cast<time_t>(localTimeSeconds);
444
445     tm localTM;
446     getLocalTime(&localTime, &localTM);
447
448     double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
449
450     if (diff < 0)
451         diff += secondsPerDay;
452
453     return (diff * msPerSecond);
454 }
455
456 // Get the DST offset, given a time in UTC
457 static double getDSTOffset(double ms, double utcOffset)
458 {
459     // On Mac OS X, the call to localtime (see getDSTOffsetSimple) will return historically accurate
460     // 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
462     // determining DST. For this reason we shift away from years that localtime can handle but would
463     // return historically accurate information.
464     int year = msToYear(ms);
465     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);
472         ms = (day * msPerDay) + msToMilliseconds(ms);
473     }
474
475     return getDSTOffsetSimple(ms / msPerSecond, utcOffset);
476 }
477
478 double gregorianDateTimeToMS(const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
479 {
480     int day = dateToDayInYear(t.year + 1900, t.month, t.monthDay);
481     double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
482     double result = (day * msPerDay) + ms;
483
484     if (!inputIsUTC) { // convert to UTC
485         double utcOffset = getUTCOffset();
486         result -= utcOffset;
487         result -= getDSTOffset(result, utcOffset);
488     }
489
490     return result;
491 }
492
493 void msToGregorianDateTime(double ms, bool outputIsUTC, GregorianDateTime& tm)
494 {
495     // input is UTC
496     double dstOff = 0.0;
497     const double utcOff = getUTCOffset();
498
499     if (!outputIsUTC) {  // convert to local time
500         dstOff = getDSTOffset(ms, utcOff);
501         ms += dstOff + utcOff;
502     }
503
504     const int year = msToYear(ms);
505     tm.second   =  msToSeconds(ms);
506     tm.minute   =  msToMinutes(ms);
507     tm.hour     =  msToHours(ms);
508     tm.weekDay  =  msToWeekDay(ms);
509     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;
513     tm.isDST    =  dstOff != 0.0;
514
515     tm.utcOffset = static_cast<long>((dstOff + utcOff) / msPerSecond);
516     tm.timeZone = NULL;
517 }
518
519 void initDateMath()
520 {
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
537 static 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".
549 static 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
568 inline 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
586 static 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
606 double parseDate(const UString &date)
607 {
608     // This parses a date in the form:
609     //     Tuesday, 09-Nov-99 23:12:40 GMT
610     // or
611     //     Sat, 01-Jan-2000 08:00:00 GMT
612     // or
613     //     Sat, 01 Jan 2000 08:00:00 GMT
614     // or
615     //     01 Jan 99 22:00 +0100    (exceptions in rfc822/rfc2822)
616     // ### non RFC formats, added for Javascript:
617     //     [Wednesday] January 09 1999 23:12:40 GMT
618     //     [Wednesday] January 09 23:12:40 GMT 1999
619     //
620     // We ignore the weekday.
621
622     CString dateCString = date.UTF8String();
623     const char *dateString = dateCString.c_str();
624      
625     // Skip leading space
626     skipSpacesAndComments(dateString);
627
628     long month = -1;
629     const char *wordStart = dateString;
630     // Check contents of first words if not number
631     while (*dateString && !isASCIIDigit(*dateString)) {
632         if (isASCIISpace(*dateString) || *dateString == '(') {
633             if (dateString - wordStart >= 3)
634                 month = findMonth(wordStart);
635             skipSpacesAndComments(dateString);
636             wordStart = dateString;
637         } else
638            dateString++;
639     }
640
641     // Missing delimiter between month and day (like "January29")?
642     if (month == -1 && wordStart != dateString)
643         month = findMonth(wordStart);
644
645     skipSpacesAndComments(dateString);
646
647     if (!*dateString)
648         return NaN;
649
650     // ' 09-Nov-99 23:12:40 GMT'
651     char *newPosStr;
652     errno = 0;
653     long day = strtol(dateString, &newPosStr, 10);
654     if (errno)
655         return NaN;
656     dateString = newPosStr;
657
658     if (!*dateString)
659         return NaN;
660
661     if (day < 0)
662         return NaN;
663
664     long year = 0;
665     if (day > 31) {
666         // ### where is the boundary and what happens below?
667         if (*dateString != '/')
668             return NaN;
669         // looks like a YYYY/MM/DD date
670         if (!*++dateString)
671             return NaN;
672         year = day;
673         month = strtol(dateString, &newPosStr, 10) - 1;
674         if (errno)
675             return NaN;
676         dateString = newPosStr;
677         if (*dateString++ != '/' || !*dateString)
678             return NaN;
679         day = strtol(dateString, &newPosStr, 10);
680         if (errno)
681             return NaN;
682         dateString = newPosStr;
683     } else if (*dateString == '/' && month == -1) {
684         dateString++;
685         // This looks like a MM/DD/YYYY date, not an RFC date.
686         month = day - 1; // 0-based
687         day = strtol(dateString, &newPosStr, 10);
688         if (errno)
689             return NaN;
690         if (day < 1 || day > 31)
691             return NaN;
692         dateString = newPosStr;
693         if (*dateString == '/')
694             dateString++;
695         if (!*dateString)
696             return NaN;
697      } else {
698         if (*dateString == '-')
699             dateString++;
700
701         skipSpacesAndComments(dateString);
702
703         if (*dateString == ',')
704             dateString++;
705
706         if (month == -1) { // not found yet
707             month = findMonth(dateString);
708             if (month == -1)
709                 return NaN;
710
711             while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
712                 dateString++;
713
714             if (!*dateString)
715                 return NaN;
716
717             // '-99 23:12:40 GMT'
718             if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
719                 return NaN;
720             dateString++;
721         }
722     }
723
724     if (month < 0 || month > 11)
725         return NaN;
726
727     // '99 23:12:40 GMT'
728     if (year <= 0 && *dateString) {
729         year = strtol(dateString, &newPosStr, 10);
730         if (errno)
731             return NaN;
732     }
733    
734     // Don't fail if the time is missing.
735     long hour = 0;
736     long minute = 0;
737     long second = 0;
738     if (!*newPosStr)
739         dateString = newPosStr;
740     else {
741         // ' 23:12:40 GMT'
742         if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
743             if (*newPosStr != ':')
744                 return NaN;
745             // There was no year; the number was the hour.
746             year = -1;
747         } else {
748             // in the normal case (we parsed the year), advance to the next number
749             dateString = ++newPosStr;
750             skipSpacesAndComments(dateString);
751         }
752
753         hour = strtol(dateString, &newPosStr, 10);
754         // Do not check for errno here since we want to continue
755         // even if errno was set becasue we are still looking
756         // for the timezone!
757
758         // Read a number? If not, this might be a timezone name.
759         if (newPosStr != dateString) {
760             dateString = newPosStr;
761
762             if (hour < 0 || hour > 23)
763                 return NaN;
764
765             if (!*dateString)
766                 return NaN;
767
768             // ':12:40 GMT'
769             if (*dateString++ != ':')
770                 return NaN;
771
772             minute = strtol(dateString, &newPosStr, 10);
773             if (errno)
774                 return NaN;
775             dateString = newPosStr;
776
777             if (minute < 0 || minute > 59)
778                 return NaN;
779
780             // ':40 GMT'
781             if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
782                 return NaN;
783
784             // seconds are optional in rfc822 + rfc2822
785             if (*dateString ==':') {
786                 dateString++;
787
788                 second = strtol(dateString, &newPosStr, 10);
789                 if (errno)
790                     return NaN;
791                 dateString = newPosStr;
792            
793                 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 == '-') {
829             long o = strtol(dateString, &newPosStr, 10);
830             if (errno)
831                 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
842                 long o2 = strtol(dateString, &newPosStr, 10);
843                 if (errno)
844                     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) {
864         year = strtol(dateString, &newPosStr, 10);
865         if (errno)
866             return NaN;
867         dateString = newPosStr;
868     }
869      
870     skipSpacesAndComments(dateString);
871      
872     // Trailing garbage
873     if (*dateString)
874         return NaN;
875
876     // Y2K: Handle 2 digit years.
877     if (year >= 0 && year < 100) {
878         if (year < 50)
879             year += 2000;
880         else
881             year += 1900;
882     }
883
884     // fall back to local timezone
885     if (!haveTZ) {
886         GregorianDateTime t;
887         t.monthDay = day;
888         t.month = month;
889         t.year = year - 1900;
890         t.isDST = -1;
891         t.second = second;
892         t.minute = minute;
893         t.hour = hour;
894
895         // Use our gregorianDateTimeToMS() rather than mktime() as the latter can't handle the full year range.
896         return gregorianDateTimeToMS(t, 0, false);
897     }
898
899     return (ymdhmsToSeconds(year, month + 1, day, hour, minute, second) - (offset * 60.0)) * msPerSecond;
900 }
901
902 double timeClip(double t)
903 {
904     if (!isfinite(t))
905         return NaN;
906     if (fabs(t) > 8.64E15)
907         return NaN;
908     return trunc(t);
909 }
910
911 UString formatDate(const GregorianDateTime &t)
912 {
913     char buffer[100];
914     snprintf(buffer, sizeof(buffer), "%s %s %02d %04d",
915         weekdayName[(t.weekDay + 6) % 7],
916         monthName[t.month], t.monthDay, t.year + 1900);
917     return buffer;
918 }
919
920 UString formatDateUTCVariant(const GregorianDateTime &t)
921 {
922     char buffer[100];
923     snprintf(buffer, sizeof(buffer), "%s, %02d %s %04d",
924         weekdayName[(t.weekDay + 6) % 7],
925         t.monthDay, monthName[t.month], t.year + 1900);
926     return buffer;
927 }
928
929 UString formatTime(const GregorianDateTime &t, bool utc)
930 {
931     char buffer[100];
932     if (utc) {
933         snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT", t.hour, t.minute, t.second);
934     } else {
935         int offset = abs(gmtoffset(t));
936         char tzname[70];
937         struct tm gtm = t;
938         strftime(tzname, sizeof(tzname), "%Z", &gtm);
939
940         if (tzname[0]) {
941             snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d (%s)",
942                 t.hour, t.minute, t.second,
943                 gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60, tzname);
944         } else {
945             snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d GMT%c%02d%02d",
946                 t.hour, t.minute, t.second,
947                 gmtoffset(t) < 0 ? '-' : '+', offset / (60*60), (offset / 60) % 60);
948         }
949     }
950     return UString(buffer);
951 }
952
953 } // namespace KJS
954
Note: See TracBrowser for help on using the browser.