date.js 31.8 KB
Newer Older
1
// Copyright 2006-2008 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


29 30
// This file relies on the fact that the following declarations have been made
// in v8natives.js:
31
// var $isFinite = GlobalIsFinite;
32

33 34 35 36 37 38 39
// -------------------------------------------------------------------

// This file contains date support implemented in JavaScript.

// Keep reference to original values of some global properties.  This
// has the added benefit that the code in this file is isolated from
// changes to these properties.
40
var $Date = global.Date;
41

42 43 44 45 46
// Helper function to throw error.
function ThrowDateTypeError() {
  throw new $TypeError('this is not a Date object.');
}

47 48 49
// ECMA 262 - 5.2
function Modulo(value, remainder) {
  var mod = value % remainder;
50 51
  // Guard against returning -0.
  if (mod == 0) return 0;
52
  return mod >= 0 ? mod : mod + remainder;
53
}
54 55 56 57


function TimeWithinDay(time) {
  return Modulo(time, msPerDay);
58
}
59 60 61 62 63 64 65


// ECMA 262 - 15.9.1.3
function DaysInYear(year) {
  if (year % 4 != 0) return 365;
  if ((year % 100 == 0) && (year % 400 != 0)) return 365;
  return 366;
66
}
67 68 69 70


function DayFromYear(year) {
  return 365 * (year-1970)
71 72 73
      + FLOOR((year-1969)/4)
      - FLOOR((year-1901)/100)
      + FLOOR((year-1601)/400);
74
}
75 76 77 78


function TimeFromYear(year) {
  return msPerDay * DayFromYear(year);
79
}
80 81 82


function InLeapYear(time) {
83
  return DaysInYear(YearFromTime(time)) - 365;  // Returns 1 or 0.
84
}
85 86 87 88


// ECMA 262 - 15.9.1.9
function EquivalentYear(year) {
89
  // Returns an equivalent year in the range [2008-2035] matching
90 91 92
  // - leap year.
  // - week day of first day.
  var time = TimeFromYear(year);
93
  var recent_year = (InLeapYear(time) == 0 ? 1967 : 1956) +
94 95 96 97
      (WeekDay(time) * 12) % 28;
  // Find the year in the range 2008..2037 that is equivalent mod 28.
  // Add 3*28 to give a positive argument to the modulus operator.
  return 2008 + (recent_year + 3*28 - 2008) % 28;
98
}
99 100 101 102


function EquivalentTime(t) {
  // The issue here is that some library calls don't work right for dates
103 104
  // that cannot be represented using a non-negative signed 32 bit integer
  // (measured in whole seconds based on the 1970 epoch).
105
  // We solve this by mapping the time to a year with same leap-year-ness
106
  // and same starting day for the year.  The ECMAscript specification says
107
  // we must do this, but for compatibility with other browsers, we use
108 109
  // the actual year if it is in the range 1970..2037
  if (t >= 0 && t <= 2.1e12) return t;
110

111 112 113
  var day = MakeDay(EquivalentYear(YearFromTime(t)),
                    MonthFromTime(t),
                    DateFromTime(t));
114
  return MakeDate(day, TimeWithinDay(t));
115
}
116

117

118 119 120 121 122 123 124 125
// local_time_offset is initialized when the DST_offset_cache is missed.
// It must not be used until after a call to DaylightSavingsOffset().
// In this way, only one check, for a DST cache miss, is needed.
var local_time_offset;


// Because computing the DST offset is an expensive operation,
// we keep a cache of the last computed DST offset along with a time interval
126
// where we know the cache is valid.
127
// When the cache is valid, local_time_offset is also valid.
128 129 130 131 132 133
var DST_offset_cache = {
  // Cached DST offset.
  offset: 0,
  // Time interval where the cached offset is valid.
  start: 0, end: -1,
  // Size of next interval expansion.
134 135
  increment: 0,
  initial_increment: 19 * msPerDay
136 137
};

138

139
// NOTE: The implementation relies on the fact that no time zones have
140 141 142 143 144 145
// more than one daylight savings offset change per 19 days.
//
// In Egypt in 2010 they decided to suspend DST during Ramadan. This
// led to a short interval where DST is in effect from September 10 to
// September 30.
//
146
// If this function is called with NaN it returns NaN.
147
function DaylightSavingsOffset(t) {
148 149 150 151 152 153 154 155 156 157 158
  // Load the cache object from the builtins object.
  var cache = DST_offset_cache;

  // Cache the start and the end in local variables for fast access.
  var start = cache.start;
  var end = cache.end;

  if (start <= t) {
    // If the time fits in the cached interval, return the cached offset.
    if (t <= end) return cache.offset;

159 160 161 162 163
    // If the cache misses, the local_time_offset may not be initialized.
    if (IS_UNDEFINED(local_time_offset)) {
      local_time_offset = %DateLocalTimeOffset();
    }

164 165 166 167 168 169 170 171 172 173
    // Compute a possible new interval end.
    var new_end = end + cache.increment;

    if (t <= new_end) {
      var end_offset = %DateDaylightSavingsOffset(EquivalentTime(new_end));
      if (cache.offset == end_offset) {
        // If the offset at the end of the new interval still matches
        // the offset in the cache, we grow the cached time interval
        // and return the offset.
        cache.end = new_end;
174
        cache.increment = cache.initial_increment;
175 176 177 178 179 180 181 182 183 184
        return end_offset;
      } else {
        var offset = %DateDaylightSavingsOffset(EquivalentTime(t));
        if (offset == end_offset) {
          // The offset at the given time is equal to the offset at the
          // new end of the interval, so that means that we've just skipped
          // the point in time where the DST offset change occurred. Updated
          // the interval to reflect this and reset the increment.
          cache.start = t;
          cache.end = new_end;
185
          cache.increment = cache.initial_increment;
186 187 188 189 190 191 192 193 194 195 196 197
        } else {
          // The interval contains a DST offset change and the given time is
          // before it. Adjust the increment to avoid a linear search for
          // the offset change point and change the end of the interval.
          cache.increment /= 3;
          cache.end = t;
        }
        // Update the offset in the cache and return it.
        cache.offset = offset;
        return offset;
      }
    }
198
  }
199

200 201 202 203
  // If the cache misses, the local_time_offset may not be initialized.
  if (IS_UNDEFINED(local_time_offset)) {
    local_time_offset = %DateLocalTimeOffset();
  }
204 205 206
  // Compute the DST offset for the time and shrink the cache interval
  // to only contain the time. This allows fast repeated DST offset
  // computations for the same time.
207
  var offset = %DateDaylightSavingsOffset(EquivalentTime(t));
208 209
  cache.offset = offset;
  cache.start = cache.end = t;
210
  cache.increment = cache.initial_increment;
211
  return offset;
212
}
213 214 215 216 217 218


var timezone_cache_time = $NaN;
var timezone_cache_timezone;

function LocalTimezone(t) {
219
  if (NUMBER_IS_NAN(t)) return "";
220
  if (t == timezone_cache_time) {
221 222 223 224 225 226
    return timezone_cache_timezone;
  }
  var timezone = %DateLocalTimezone(EquivalentTime(t));
  timezone_cache_time = t;
  timezone_cache_timezone = timezone;
  return timezone;
227
}
228 229 230


function WeekDay(time) {
231
  return Modulo(DAY(time) + 4, 7);
232
}
233 234 235


function LocalTime(time) {
236
  if (NUMBER_IS_NAN(time)) return time;
237 238
  // DaylightSavingsOffset called before local_time_offset used.
  return time + DaylightSavingsOffset(time) + local_time_offset;
239
}
240

241 242

var ltcache = {
243
  key: null,
244 245 246
  val: null
};

247
function LocalTimeNoCheck(time) {
248 249
  var ltc = ltcache;
  if (%_ObjectEquals(time, ltc.key)) return ltc.val;
250

251
  // Inline the DST offset cache checks for speed.
252 253
  // The cache is hit, or DaylightSavingsOffset is called,
  // before local_time_offset is used.
254 255 256 257 258 259
  var cache = DST_offset_cache;
  if (cache.start <= time && time <= cache.end) {
    var dst_offset = cache.offset;
  } else {
    var dst_offset = DaylightSavingsOffset(time);
  }
260 261
  ltc.key = time;
  return (ltc.val = time + local_time_offset + dst_offset);
262 263
}

264 265

function UTC(time) {
266
  if (NUMBER_IS_NAN(time)) return time;
267 268 269 270 271
  // local_time_offset is needed before the call to DaylightSavingsOffset,
  // so it may be uninitialized.
  if (IS_UNDEFINED(local_time_offset)) {
    local_time_offset = %DateLocalTimeOffset();
  }
272
  var tmp = time - local_time_offset;
273
  return tmp - DaylightSavingsOffset(tmp);
274
}
275 276 277 278 279 280 281 282 283 284 285 286


// ECMA 262 - 15.9.1.11
function MakeTime(hour, min, sec, ms) {
  if (!$isFinite(hour)) return $NaN;
  if (!$isFinite(min)) return $NaN;
  if (!$isFinite(sec)) return $NaN;
  if (!$isFinite(ms)) return $NaN;
  return TO_INTEGER(hour) * msPerHour
      + TO_INTEGER(min) * msPerMinute
      + TO_INTEGER(sec) * msPerSecond
      + TO_INTEGER(ms);
287
}
288 289 290 291 292


// ECMA 262 - 15.9.1.12
function TimeInYear(year) {
  return DaysInYear(year) * msPerDay;
293
}
294 295


296 297
var ymd_from_time_cache = [1970, 0, 1];
var ymd_from_time_cached_time = 0;
298 299 300

function YearFromTime(t) {
  if (t !== ymd_from_time_cached_time) {
301
    if (!$isFinite(t)) {
302 303 304 305
      return $NaN;
    }

    %DateYMDFromTime(t, ymd_from_time_cache);
306
    ymd_from_time_cached_time = t;
307
  }
308 309 310 311 312 313

  return ymd_from_time_cache[0];
}

function MonthFromTime(t) {
  if (t !== ymd_from_time_cached_time) {
314
    if (!$isFinite(t)) {
315 316 317
      return $NaN;
    }
    %DateYMDFromTime(t, ymd_from_time_cache);
318
    ymd_from_time_cached_time = t;
319
  }
320 321 322 323 324 325

  return ymd_from_time_cache[1];
}

function DateFromTime(t) {
  if (t !== ymd_from_time_cached_time) {
326
    if (!$isFinite(t)) {
327 328 329 330
      return $NaN;
    }

    %DateYMDFromTime(t, ymd_from_time_cache);
331
    ymd_from_time_cached_time = t;
332 333 334
  }

  return ymd_from_time_cache[2];
335
}
336

337

338 339 340 341 342 343 344 345 346
// Compute number of days given a year, month, date.
// Note that month and date can lie outside the normal range.
//   For example:
//     MakeDay(2007, -4, 20) --> MakeDay(2006, 8, 20)
//     MakeDay(2007, -33, 1) --> MakeDay(2004, 3, 1)
//     MakeDay(2007, 14, -50) --> MakeDay(2007, 8, 11)
function MakeDay(year, month, date) {
  if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) return $NaN;

347 348 349 350
  // Convert to integer and map -0 to 0.
  year = TO_INTEGER_MAP_MINUS_ZERO(year);
  month = TO_INTEGER_MAP_MINUS_ZERO(month);
  date = TO_INTEGER_MAP_MINUS_ZERO(date);
351

352
  if (year < kMinYear || year > kMaxYear ||
353
      month < kMinMonth || month > kMaxMonth) {
354
    return $NaN;
355 356
  }

357 358
  // Now we rely on year and month being SMIs.
  return %DateMakeDay(year, month) + date - 1;
359
}
360 361 362 363


// ECMA 262 - 15.9.1.13
function MakeDate(day, time) {
364 365 366 367 368 369 370 371
  var time = day * msPerDay + time;
  // Some of our runtime funtions for computing UTC(time) rely on
  // times not being significantly larger than MAX_TIME_MS. If there
  // is no way that the time can be within range even after UTC
  // conversion we return NaN immediately instead of relying on
  // TimeClip to do it.
  if ($abs(time) > MAX_TIME_BEFORE_UTC) return $NaN;
  return time;
372
}
373 374 375 376 377


// ECMA 262 - 15.9.1.14
function TimeClip(time) {
  if (!$isFinite(time)) return $NaN;
378
  if ($abs(time) > MAX_TIME_MS) return $NaN;
379
  return TO_INTEGER(time);
380
}
381 382


383 384 385 386 387 388 389 390 391 392 393 394 395
// The Date cache is used to limit the cost of parsing the same Date
// strings over and over again.
var Date_cache = {
  // Cached time value.
  time: $NaN,
  // Cached year when interpreting the time as a local time. Only
  // valid when the time matches cached time.
  year: $NaN,
  // String input for which the cached time is valid.
  string: null
};


396
%SetCode($Date, function(year, month, date, hours, minutes, seconds, ms) {
397 398 399 400 401 402 403 404 405 406 407 408 409 410
  if (!%_IsConstructCall()) {
    // ECMA 262 - 15.9.2
    return (new $Date()).toString();
  }

  // ECMA 262 - 15.9.3
  var argc = %_ArgumentsLength();
  var value;
  if (argc == 0) {
    value = %DateCurrentTime();

  } else if (argc == 1) {
    if (IS_NUMBER(year)) {
      value = TimeClip(year);
411 412 413 414 415 416 417 418 419

    } else if (IS_STRING(year)) {
      // Probe the Date cache. If we already have a time value for the
      // given time, we re-use that instead of parsing the string again.
      var cache = Date_cache;
      if (cache.string === year) {
        value = cache.time;
      } else {
        value = DateParse(year);
420 421
        if (!NUMBER_IS_NAN(value)) {
          cache.time = value;
422
          cache.year = YearFromTime(LocalTimeNoCheck(value));
423 424
          cache.string = year;
        }
425 426
      }

427
    } else {
428
      // According to ECMA 262, no hint should be given for this
429 430
      // conversion. However, ToPrimitive defaults to STRING_HINT for
      // Date objects which will lose precision when the Date
431
      // constructor is called with another Date object as its
432 433 434
      // argument. We therefore use NUMBER_HINT for the conversion,
      // which is the default for everything else than Date objects.
      // This makes us behave like KJS and SpiderMonkey.
435
      var time = ToPrimitive(year, NUMBER_HINT);
436
      value = IS_STRING(time) ? DateParse(time) : TimeClip(ToNumber(time));
437
    }
438 439

  } else {
440 441 442 443 444 445 446
    year = ToNumber(year);
    month = ToNumber(month);
    date = argc > 2 ? ToNumber(date) : 1;
    hours = argc > 3 ? ToNumber(hours) : 0;
    minutes = argc > 4 ? ToNumber(minutes) : 0;
    seconds = argc > 5 ? ToNumber(seconds) : 0;
    ms = argc > 6 ? ToNumber(ms) : 0;
447 448 449
    year = (!NUMBER_IS_NAN(year) &&
            0 <= TO_INTEGER(year) &&
            TO_INTEGER(year) <= 99) ? 1900 + TO_INTEGER(year) : year;
450 451
    var day = MakeDay(year, month, date);
    var time = MakeTime(hours, minutes, seconds, ms);
452
    value = TimeClip(UTC(MakeDate(day, time)));
453
  }
454
  %_SetValueOf(this, value);
455 456 457 458 459 460 461
});


%FunctionSetPrototype($Date, new $Date($NaN));


var WeekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
462 463
var Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
              'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
464 465 466 467


function TwoDigitString(value) {
  return value < 10 ? "0" + value : "" + value;
468
}
469 470 471 472


function DateString(time) {
  return WeekDays[WeekDay(time)] + ' '
473 474 475
      + Months[MonthFromTime(time)] + ' '
      + TwoDigitString(DateFromTime(time)) + ' '
      + YearFromTime(time);
476
}
477 478


479 480 481 482
var LongWeekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
    'Thursday', 'Friday', 'Saturday'];
var LongMonths = ['January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'];
483 484 485 486


function LongDateString(time) {
  return LongWeekDays[WeekDay(time)] + ', '
487 488 489
      + LongMonths[MonthFromTime(time)] + ' '
      + TwoDigitString(DateFromTime(time)) + ', '
      + YearFromTime(time);
490 491 492
}


493
function TimeString(time) {
494 495 496
  return TwoDigitString(HOUR_FROM_TIME(time)) + ':'
      + TwoDigitString(MIN_FROM_TIME(time)) + ':'
      + TwoDigitString(SEC_FROM_TIME(time));
497
}
498 499 500


function LocalTimezoneString(time) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514
  var old_timezone = timezone_cache_timezone;
  var timezone = LocalTimezone(time);
  if (old_timezone && timezone != old_timezone) {
    // If the timezone string has changed from the one that we cached,
    // the local time offset may now be wrong. So we need to update it
    // and try again.
    local_time_offset = %DateLocalTimeOffset();
    // We also need to invalidate the DST cache as the new timezone may have
    // different DST times.
    var dst_cache = DST_offset_cache;
    dst_cache.start = 0;
    dst_cache.end = -1;
  }

515
  var timezoneOffset =
516
      (DaylightSavingsOffset(time) + local_time_offset) / msPerMinute;
517
  var sign = (timezoneOffset >= 0) ? 1 : -1;
518 519
  var hours = FLOOR((sign * timezoneOffset)/60);
  var min   = FLOOR((sign * timezoneOffset)%60);
520 521
  var gmt = ' GMT' + ((sign == 1) ? '+' : '-') +
      TwoDigitString(hours) + TwoDigitString(min);
522
  return gmt + ' (' +  timezone + ')';
523
}
524 525 526 527


function DatePrintString(time) {
  return DateString(time) + ' ' + TimeString(time);
528
}
529 530 531

// -------------------------------------------------------------------

532
// Reused output buffer. Used when parsing date strings.
533
var parse_buffer = $Array(8);
534 535 536

// ECMA 262 - 15.9.4.2
function DateParse(string) {
537
  var arr = %DateParseString(ToString(string), parse_buffer);
538 539 540
  if (IS_NULL(arr)) return $NaN;

  var day = MakeDay(arr[0], arr[1], arr[2]);
541
  var time = MakeTime(arr[3], arr[4], arr[5], arr[6]);
542
  var date = MakeDate(day, time);
543

544
  if (IS_NULL(arr[7])) {
545 546
    return TimeClip(UTC(date));
  } else {
547
    return TimeClip(date - arr[7] * 1000);
548
  }
549
}
550 551 552 553 554 555 556 557 558 559 560 561


// ECMA 262 - 15.9.4.3
function DateUTC(year, month, date, hours, minutes, seconds, ms) {
  year = ToNumber(year);
  month = ToNumber(month);
  var argc = %_ArgumentsLength();
  date = argc > 2 ? ToNumber(date) : 1;
  hours = argc > 3 ? ToNumber(hours) : 0;
  minutes = argc > 4 ? ToNumber(minutes) : 0;
  seconds = argc > 5 ? ToNumber(seconds) : 0;
  ms = argc > 6 ? ToNumber(ms) : 0;
562 563 564
  year = (!NUMBER_IS_NAN(year) &&
          0 <= TO_INTEGER(year) &&
          TO_INTEGER(year) <= 99) ? 1900 + TO_INTEGER(year) : year;
565 566 567
  var day = MakeDay(year, month, date);
  var time = MakeTime(hours, minutes, seconds, ms);
  return %_SetValueOf(this, TimeClip(MakeDate(day, time)));
568
}
569 570 571 572 573


// Mozilla-specific extension. Returns the number of milliseconds
// elapsed since 1 January 1970 00:00:00 UTC.
function DateNow() {
574
  return %DateCurrentTime();
575
}
576 577 578 579


// ECMA 262 - 15.9.5.2
function DateToString() {
580 581
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
582 583
  var time_zone_string = LocalTimezoneString(t);  // May update local offset.
  return DatePrintString(LocalTimeNoCheck(t)) + time_zone_string;
584
}
585 586 587 588


// ECMA 262 - 15.9.5.3
function DateToDateString() {
589 590
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
591
  return DateString(LocalTimeNoCheck(t));
592
}
593 594 595 596


// ECMA 262 - 15.9.5.4
function DateToTimeString() {
597 598
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
599 600
  var time_zone_string = LocalTimezoneString(t);  // May update local offset.
  return TimeString(LocalTimeNoCheck(t)) + time_zone_string;
601 602 603 604 605
}


// ECMA 262 - 15.9.5.5
function DateToLocaleString() {
606
  return %_CallFunction(this, DateToString);
607 608 609 610 611
}


// ECMA 262 - 15.9.5.6
function DateToLocaleDateString() {
612 613
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
614
  return LongDateString(LocalTimeNoCheck(t));
615
}
616 617


618 619
// ECMA 262 - 15.9.5.7
function DateToLocaleTimeString() {
620 621
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
622
  var lt = LocalTimeNoCheck(t);
623
  return TimeString(lt);
624 625 626 627 628
}


// ECMA 262 - 15.9.5.8
function DateValueOf() {
629
  return DATE_VALUE(this);
630
}
631 632


633 634
// ECMA 262 - 15.9.5.9
function DateGetTime() {
635
  return DATE_VALUE(this);
636 637 638 639 640
}


// ECMA 262 - 15.9.5.10
function DateGetFullYear() {
641 642 643 644
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  var cache = Date_cache;
  if (cache.time === t) return cache.year;
645
  return YearFromTime(LocalTimeNoCheck(t));
646
}
647 648 649 650


// ECMA 262 - 15.9.5.11
function DateGetUTCFullYear() {
651 652
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
653
  return YearFromTime(t);
654
}
655 656 657 658


// ECMA 262 - 15.9.5.12
function DateGetMonth() {
659 660
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
661
  return MonthFromTime(LocalTimeNoCheck(t));
662
}
663 664 665 666


// ECMA 262 - 15.9.5.13
function DateGetUTCMonth() {
667 668
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
669
  return MonthFromTime(t);
670
}
671 672 673 674


// ECMA 262 - 15.9.5.14
function DateGetDate() {
675 676
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
677
  return DateFromTime(LocalTimeNoCheck(t));
678
}
679 680 681 682


// ECMA 262 - 15.9.5.15
function DateGetUTCDate() {
683 684
  var t = DATE_VALUE(this);
  return NAN_OR_DATE_FROM_TIME(t);
685
}
686 687 688 689


// ECMA 262 - 15.9.5.16
function DateGetDay() {
690
  var t = DATE_VALUE(this);
691
  if (NUMBER_IS_NAN(t)) return t;
692
  return WeekDay(LocalTimeNoCheck(t));
693
}
694 695 696 697


// ECMA 262 - 15.9.5.17
function DateGetUTCDay() {
698
  var t = DATE_VALUE(this);
699
  if (NUMBER_IS_NAN(t)) return t;
700
  return WeekDay(t);
701
}
702 703 704 705


// ECMA 262 - 15.9.5.18
function DateGetHours() {
706 707 708
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return HOUR_FROM_TIME(LocalTimeNoCheck(t));
709
}
710 711 712 713


// ECMA 262 - 15.9.5.19
function DateGetUTCHours() {
714 715 716
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return HOUR_FROM_TIME(t);
717
}
718 719 720 721


// ECMA 262 - 15.9.5.20
function DateGetMinutes() {
722 723 724
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return MIN_FROM_TIME(LocalTimeNoCheck(t));
725
}
726 727 728 729


// ECMA 262 - 15.9.5.21
function DateGetUTCMinutes() {
730 731
  var t = DATE_VALUE(this);
  return NAN_OR_MIN_FROM_TIME(t);
732
}
733 734 735 736


// ECMA 262 - 15.9.5.22
function DateGetSeconds() {
737 738 739
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return SEC_FROM_TIME(LocalTimeNoCheck(t));
740
}
741 742 743 744


// ECMA 262 - 15.9.5.23
function DateGetUTCSeconds() {
745 746
  var t = DATE_VALUE(this);
  return NAN_OR_SEC_FROM_TIME(t);
747
}
748 749 750 751


// ECMA 262 - 15.9.5.24
function DateGetMilliseconds() {
752 753 754
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
  return MS_FROM_TIME(LocalTimeNoCheck(t));
755
}
756 757 758 759


// ECMA 262 - 15.9.5.25
function DateGetUTCMilliseconds() {
760 761
  var t = DATE_VALUE(this);
  return NAN_OR_MS_FROM_TIME(t);
762
}
763 764 765 766


// ECMA 262 - 15.9.5.26
function DateGetTimezoneOffset() {
767 768
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return t;
769
  return (t - LocalTimeNoCheck(t)) / msPerMinute;
770
}
771 772 773 774


// ECMA 262 - 15.9.5.27
function DateSetTime(ms) {
775
  if (!IS_DATE(this)) ThrowDateTypeError();
776
  return %_SetValueOf(this, TimeClip(ToNumber(ms)));
777
}
778 779 780 781


// ECMA 262 - 15.9.5.28
function DateSetMilliseconds(ms) {
782
  var t = LocalTime(DATE_VALUE(this));
783
  ms = ToNumber(ms);
784 785 786 787
  var time = MakeTime(HOUR_FROM_TIME(t),
                      MIN_FROM_TIME(t),
                      SEC_FROM_TIME(t),
                      ms);
788
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(DAY(t), time))));
789
}
790 791 792 793


// ECMA 262 - 15.9.5.29
function DateSetUTCMilliseconds(ms) {
794
  var t = DATE_VALUE(this);
795
  ms = ToNumber(ms);
796 797 798 799
  var time = MakeTime(HOUR_FROM_TIME(t),
                      MIN_FROM_TIME(t),
                      SEC_FROM_TIME(t),
                      ms);
800
  return %_SetValueOf(this, TimeClip(MakeDate(DAY(t), time)));
801
}
802 803 804 805


// ECMA 262 - 15.9.5.30
function DateSetSeconds(sec, ms) {
806
  var t = LocalTime(DATE_VALUE(this));
807
  sec = ToNumber(sec);
808
  ms = %_ArgumentsLength() < 2 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
809 810
  var time = MakeTime(HOUR_FROM_TIME(t), MIN_FROM_TIME(t), sec, ms);
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(DAY(t), time))));
811
}
812 813 814 815


// ECMA 262 - 15.9.5.31
function DateSetUTCSeconds(sec, ms) {
816
  var t = DATE_VALUE(this);
817
  sec = ToNumber(sec);
818
  ms = %_ArgumentsLength() < 2 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
819 820
  var time = MakeTime(HOUR_FROM_TIME(t), MIN_FROM_TIME(t), sec, ms);
  return %_SetValueOf(this, TimeClip(MakeDate(DAY(t), time)));
821
}
822 823 824 825


// ECMA 262 - 15.9.5.33
function DateSetMinutes(min, sec, ms) {
826
  var t = LocalTime(DATE_VALUE(this));
827 828
  min = ToNumber(min);
  var argc = %_ArgumentsLength();
829 830
  sec = argc < 2 ? NAN_OR_SEC_FROM_TIME(t) : ToNumber(sec);
  ms = argc < 3 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
831 832
  var time = MakeTime(HOUR_FROM_TIME(t), min, sec, ms);
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(DAY(t), time))));
833
}
834 835 836 837


// ECMA 262 - 15.9.5.34
function DateSetUTCMinutes(min, sec, ms) {
838
  var t = DATE_VALUE(this);
839 840
  min = ToNumber(min);
  var argc = %_ArgumentsLength();
841 842
  sec = argc < 2 ? NAN_OR_SEC_FROM_TIME(t) : ToNumber(sec);
  ms = argc < 3 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
843 844
  var time = MakeTime(HOUR_FROM_TIME(t), min, sec, ms);
  return %_SetValueOf(this, TimeClip(MakeDate(DAY(t), time)));
845
}
846 847 848 849


// ECMA 262 - 15.9.5.35
function DateSetHours(hour, min, sec, ms) {
850
  var t = LocalTime(DATE_VALUE(this));
851 852
  hour = ToNumber(hour);
  var argc = %_ArgumentsLength();
853 854 855
  min = argc < 2 ? NAN_OR_MIN_FROM_TIME(t) : ToNumber(min);
  sec = argc < 3 ? NAN_OR_SEC_FROM_TIME(t) : ToNumber(sec);
  ms = argc < 4 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
856
  var time = MakeTime(hour, min, sec, ms);
857
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(DAY(t), time))));
858
}
859 860 861 862


// ECMA 262 - 15.9.5.34
function DateSetUTCHours(hour, min, sec, ms) {
863
  var t = DATE_VALUE(this);
864 865
  hour = ToNumber(hour);
  var argc = %_ArgumentsLength();
866 867 868
  min = argc < 2 ? NAN_OR_MIN_FROM_TIME(t) : ToNumber(min);
  sec = argc < 3 ? NAN_OR_SEC_FROM_TIME(t) : ToNumber(sec);
  ms = argc < 4 ? NAN_OR_MS_FROM_TIME(t) : ToNumber(ms);
869
  var time = MakeTime(hour, min, sec, ms);
870
  return %_SetValueOf(this, TimeClip(MakeDate(DAY(t), time)));
871
}
872 873 874 875


// ECMA 262 - 15.9.5.36
function DateSetDate(date) {
876
  var t = LocalTime(DATE_VALUE(this));
877
  date = ToNumber(date);
878
  var day = MakeDay(YearFromTime(t), MonthFromTime(t), date);
879
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(day, TimeWithinDay(t)))));
880
}
881 882 883 884


// ECMA 262 - 15.9.5.37
function DateSetUTCDate(date) {
885
  var t = DATE_VALUE(this);
886
  date = ToNumber(date);
887
  var day = MakeDay(YearFromTime(t), MonthFromTime(t), date);
888
  return %_SetValueOf(this, TimeClip(MakeDate(day, TimeWithinDay(t))));
889
}
890 891 892 893


// ECMA 262 - 15.9.5.38
function DateSetMonth(month, date) {
894
  var t = LocalTime(DATE_VALUE(this));
895
  month = ToNumber(month);
896
  date = %_ArgumentsLength() < 2 ? NAN_OR_DATE_FROM_TIME(t) : ToNumber(date);
897
  var day = MakeDay(YearFromTime(t), month, date);
898
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(day, TimeWithinDay(t)))));
899
}
900 901 902 903


// ECMA 262 - 15.9.5.39
function DateSetUTCMonth(month, date) {
904
  var t = DATE_VALUE(this);
905
  month = ToNumber(month);
906
  date = %_ArgumentsLength() < 2 ? NAN_OR_DATE_FROM_TIME(t) : ToNumber(date);
907
  var day = MakeDay(YearFromTime(t), month, date);
908
  return %_SetValueOf(this, TimeClip(MakeDate(day, TimeWithinDay(t))));
909
}
910 911 912 913


// ECMA 262 - 15.9.5.40
function DateSetFullYear(year, month, date) {
914 915
  var t = DATE_VALUE(this);
  t = NUMBER_IS_NAN(t) ? 0 : LocalTimeNoCheck(t);
916 917
  year = ToNumber(year);
  var argc = %_ArgumentsLength();
918 919
  month = argc < 2 ? MonthFromTime(t) : ToNumber(month);
  date = argc < 3 ? DateFromTime(t) : ToNumber(date);
920 921
  var day = MakeDay(year, month, date);
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(day, TimeWithinDay(t)))));
922
}
923 924 925 926


// ECMA 262 - 15.9.5.41
function DateSetUTCFullYear(year, month, date) {
927 928
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) t = 0;
929 930
  var argc = %_ArgumentsLength();
  year = ToNumber(year);
931 932
  month = argc < 2 ? MonthFromTime(t) : ToNumber(month);
  date = argc < 3 ? DateFromTime(t) : ToNumber(date);
933 934
  var day = MakeDay(year, month, date);
  return %_SetValueOf(this, TimeClip(MakeDate(day, TimeWithinDay(t))));
935
}
936 937 938 939


// ECMA 262 - 15.9.5.42
function DateToUTCString() {
940 941
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return kInvalidDate;
942 943
  // Return UTC string of the form: Sat, 31 Jan 1970 23:00:00 GMT
  return WeekDays[WeekDay(t)] + ', '
944 945 946
      + TwoDigitString(DateFromTime(t)) + ' '
      + Months[MonthFromTime(t)] + ' '
      + YearFromTime(t) + ' '
947
      + TimeString(t) + ' GMT';
948
}
949 950 951 952


// ECMA 262 - B.2.4
function DateGetYear() {
953 954
  var t = DATE_VALUE(this);
  if (NUMBER_IS_NAN(t)) return $NaN;
955
  return YearFromTime(LocalTimeNoCheck(t)) - 1900;
956
}
957 958 959 960


// ECMA 262 - B.2.5
function DateSetYear(year) {
961 962
  var t = LocalTime(DATE_VALUE(this));
  if (NUMBER_IS_NAN(t)) t = 0;
963
  year = ToNumber(year);
964
  if (NUMBER_IS_NAN(year)) return %_SetValueOf(this, $NaN);
965 966
  year = (0 <= TO_INTEGER(year) && TO_INTEGER(year) <= 99)
      ? 1900 + TO_INTEGER(year) : year;
967
  var day = MakeDay(year, MonthFromTime(t), DateFromTime(t));
968
  return %_SetValueOf(this, TimeClip(UTC(MakeDate(day, TimeWithinDay(t)))));
969 970 971 972 973 974 975 976 977 978 979
}


// ECMA 262 - B.2.6
//
// Notice that this does not follow ECMA 262 completely.  ECMA 262
// says that toGMTString should be the same Function object as
// toUTCString.  JSC does not do this, so for compatibility we do not
// do that either.  Instead, we create a new function whose name
// property will return toGMTString.
function DateToGMTString() {
980
  return %_CallFunction(this, DateToUTCString);
981
}
982 983


984 985 986
function PadInt(n, digits) {
  if (digits == 1) return n;
  return n < MathPow(10, digits - 1) ? '0' + PadInt(n, digits - 1) : n;
987 988 989
}


990
// ECMA 262 - 15.9.5.43
991
function DateToISOString() {
992
  var t = DATE_VALUE(this);
993
  if (NUMBER_IS_NAN(t)) throw MakeRangeError("invalid_time_value", []);
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  var year = this.getUTCFullYear();
  var year_string;
  if (year >= 0 && year <= 9999) {
    year_string = PadInt(year, 4);
  } else {
    if (year < 0) {
      year_string = "-" + PadInt(-year, 6);
    } else {
      year_string = "+" + PadInt(year, 6);
    }
  }
  return year_string +
1006
      '-' + PadInt(this.getUTCMonth() + 1, 2) +
1007
      '-' + PadInt(this.getUTCDate(), 2) +
1008
      'T' + PadInt(this.getUTCHours(), 2) +
1009
      ':' + PadInt(this.getUTCMinutes(), 2) +
1010
      ':' + PadInt(this.getUTCSeconds(), 2) +
1011
      '.' + PadInt(this.getUTCMilliseconds(), 3) +
1012 1013 1014 1015 1016
      'Z';
}


function DateToJSON(key) {
1017 1018
  var o = ToObject(this);
  var tv = DefaultNumber(o);
1019 1020
  if (IS_NUMBER(tv) && !NUMBER_IS_FINITE(tv)) {
    return null;
1021 1022
  }
  return o.toISOString();
1023 1024 1025
}


1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
function ResetDateCache() {

  // Reset the local_time_offset:
  local_time_offset = %DateLocalTimeOffset();

  // Reset the DST offset cache:
  var cache = DST_offset_cache;
  cache.offset = 0;
  cache.start = 0;
  cache.end = -1;
  cache.increment = 0;
  cache.initial_increment = 19 * msPerDay;

  // Reset the timezone cache:
  timezone_cache_time = $NaN;
  timezone_cache_timezone = undefined;

  // Reset the ltcache:
  ltcache.key = null;
  ltcache.val = null;

  // Reset the ymd_from_time_cache:
  ymd_from_time_cache = [$NaN, $NaN, $NaN];
  ymd_from_time_cached_time = $NaN;

  // Reset the date cache:
  cache = Date_cache;
  cache.time = $NaN;
  cache.year = $NaN;
  cache.string = null;
}


1059 1060
// -------------------------------------------------------------------

1061 1062 1063
function SetUpDate() {
  %CheckIsBootstrapping();
  // Set up non-enumerable properties of the Date object itself.
1064 1065 1066 1067 1068 1069
  InstallFunctions($Date, DONT_ENUM, $Array(
    "UTC", DateUTC,
    "parse", DateParse,
    "now", DateNow
  ));

1070
  // Set up non-enumerable constructor property of the Date prototype object.
1071
  %SetProperty($Date.prototype, "constructor", $Date, DONT_ENUM);
1072

1073
  // Set up non-enumerable functions of the Date prototype object and
1074
  // set their names.
1075
  InstallFunctions($Date.prototype, DONT_ENUM, $Array(
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    "toString", DateToString,
    "toDateString", DateToDateString,
    "toTimeString", DateToTimeString,
    "toLocaleString", DateToLocaleString,
    "toLocaleDateString", DateToLocaleDateString,
    "toLocaleTimeString", DateToLocaleTimeString,
    "valueOf", DateValueOf,
    "getTime", DateGetTime,
    "getFullYear", DateGetFullYear,
    "getUTCFullYear", DateGetUTCFullYear,
    "getMonth", DateGetMonth,
    "getUTCMonth", DateGetUTCMonth,
    "getDate", DateGetDate,
    "getUTCDate", DateGetUTCDate,
    "getDay", DateGetDay,
    "getUTCDay", DateGetUTCDay,
    "getHours", DateGetHours,
    "getUTCHours", DateGetUTCHours,
    "getMinutes", DateGetMinutes,
    "getUTCMinutes", DateGetUTCMinutes,
    "getSeconds", DateGetSeconds,
    "getUTCSeconds", DateGetUTCSeconds,
    "getMilliseconds", DateGetMilliseconds,
    "getUTCMilliseconds", DateGetUTCMilliseconds,
    "getTimezoneOffset", DateGetTimezoneOffset,
    "setTime", DateSetTime,
    "setMilliseconds", DateSetMilliseconds,
    "setUTCMilliseconds", DateSetUTCMilliseconds,
    "setSeconds", DateSetSeconds,
    "setUTCSeconds", DateSetUTCSeconds,
    "setMinutes", DateSetMinutes,
    "setUTCMinutes", DateSetUTCMinutes,
    "setHours", DateSetHours,
    "setUTCHours", DateSetUTCHours,
    "setDate", DateSetDate,
    "setUTCDate", DateSetUTCDate,
    "setMonth", DateSetMonth,
    "setUTCMonth", DateSetUTCMonth,
    "setFullYear", DateSetFullYear,
    "setUTCFullYear", DateSetUTCFullYear,
    "toGMTString", DateToGMTString,
    "toUTCString", DateToUTCString,
    "getYear", DateGetYear,
1119 1120 1121
    "setYear", DateSetYear,
    "toISOString", DateToISOString,
    "toJSON", DateToJSON
1122 1123
  ));
}
1124

1125
SetUpDate();