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

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

2008-06-29 Sam Weinig <[email protected]>

Fix non-AllInOne build.

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