1 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 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 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 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 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
//! Boa's implementation of ECMAScript's `Date` object.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-date-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
use crate::{
builtins::{
date::utils::{
date_from_time, date_string, day, hour_from_time, local_time, make_date, make_day,
make_full_year, make_time, min_from_time, month_from_time, ms_from_time, pad_five,
pad_four, pad_six, pad_three, pad_two, parse_date, sec_from_time, time_clip,
time_string, time_within_day, time_zone_string, to_date_string_t, utc_t, week_day,
year_from_time, MS_PER_MINUTE,
},
BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject,
},
context::{
intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
HostHooks,
},
error::JsNativeError,
js_string,
object::{internal_methods::get_prototype_from_constructor, JsObject},
property::Attribute,
realm::Realm,
string::{common::StaticJsStrings, utf16},
symbol::JsSymbol,
value::{JsValue, PreferredType},
Context, JsArgs, JsData, JsError, JsResult, JsString,
};
use boa_gc::{Finalize, Trace};
use boa_profiler::Profiler;
pub(crate) mod utils;
#[cfg(test)]
mod tests;
/// The internal representation of a `Date` object.
#[derive(Debug, Copy, Clone, Trace, Finalize, JsData)]
#[boa_gc(empty_trace)]
pub struct Date(f64);
impl Date {
/// Creates a new `Date`.
pub(crate) const fn new(dt: f64) -> Self {
Self(dt)
}
/// Creates a new `Date` from the current UTC time of the host.
pub(crate) fn utc_now(hooks: &dyn HostHooks) -> Self {
Self(hooks.utc_now() as f64)
}
}
impl IntrinsicObject for Date {
fn init(realm: &Realm) {
let _timer = Profiler::global().start_event(std::any::type_name::<Self>(), "init");
let to_utc_string = BuiltInBuilder::callable(realm, Self::to_utc_string)
.name(js_string!("toUTCString"))
.length(0)
.build();
let to_primitive = BuiltInBuilder::callable(realm, Self::to_primitive)
.name(js_string!("[Symbol.toPrimitive]"))
.length(1)
.build();
BuiltInBuilder::from_standard_constructor::<Self>(realm)
.static_method(Self::now, js_string!("now"), 0)
.static_method(Self::parse, js_string!("parse"), 1)
.static_method(Self::utc, js_string!("UTC"), 7)
.method(Self::get_date::<true>, js_string!("getDate"), 0)
.method(Self::get_day::<true>, js_string!("getDay"), 0)
.method(Self::get_full_year::<true>, js_string!("getFullYear"), 0)
.method(Self::get_hours::<true>, js_string!("getHours"), 0)
.method(
Self::get_milliseconds::<true>,
js_string!("getMilliseconds"),
0,
)
.method(Self::get_minutes::<true>, js_string!("getMinutes"), 0)
.method(Self::get_month::<true>, js_string!("getMonth"), 0)
.method(Self::get_seconds::<true>, js_string!("getSeconds"), 0)
.method(Self::get_time, js_string!("getTime"), 0)
.method(
Self::get_timezone_offset,
js_string!("getTimezoneOffset"),
0,
)
.method(Self::get_date::<false>, js_string!("getUTCDate"), 0)
.method(Self::get_day::<false>, js_string!("getUTCDay"), 0)
.method(
Self::get_full_year::<false>,
js_string!("getUTCFullYear"),
0,
)
.method(Self::get_hours::<false>, js_string!("getUTCHours"), 0)
.method(
Self::get_milliseconds::<false>,
js_string!("getUTCMilliseconds"),
0,
)
.method(Self::get_minutes::<false>, js_string!("getUTCMinutes"), 0)
.method(Self::get_month::<false>, js_string!("getUTCMonth"), 0)
.method(Self::get_seconds::<false>, js_string!("getUTCSeconds"), 0)
.method(Self::get_year, js_string!("getYear"), 0)
.method(Self::set_date::<true>, js_string!("setDate"), 1)
.method(Self::set_full_year::<true>, js_string!("setFullYear"), 3)
.method(Self::set_hours::<true>, js_string!("setHours"), 4)
.method(
Self::set_milliseconds::<true>,
js_string!("setMilliseconds"),
1,
)
.method(Self::set_minutes::<true>, js_string!("setMinutes"), 3)
.method(Self::set_month::<true>, js_string!("setMonth"), 2)
.method(Self::set_seconds::<true>, js_string!("setSeconds"), 2)
.method(Self::set_time, js_string!("setTime"), 1)
.method(Self::set_date::<false>, js_string!("setUTCDate"), 1)
.method(
Self::set_full_year::<false>,
js_string!("setUTCFullYear"),
3,
)
.method(Self::set_hours::<false>, js_string!("setUTCHours"), 4)
.method(
Self::set_milliseconds::<false>,
js_string!("setUTCMilliseconds"),
1,
)
.method(Self::set_minutes::<false>, js_string!("setUTCMinutes"), 3)
.method(Self::set_month::<false>, js_string!("setUTCMonth"), 2)
.method(Self::set_seconds::<false>, js_string!("setUTCSeconds"), 2)
.method(Self::set_year, js_string!("setYear"), 1)
.method(Self::to_date_string, js_string!("toDateString"), 0)
.method(Self::to_iso_string, js_string!("toISOString"), 0)
.method(Self::to_json, js_string!("toJSON"), 1)
.method(
Self::to_locale_date_string,
js_string!("toLocaleDateString"),
0,
)
.method(Self::to_locale_string, js_string!("toLocaleString"), 0)
.method(
Self::to_locale_time_string,
js_string!("toLocaleTimeString"),
0,
)
.method(Self::to_string, js_string!("toString"), 0)
.method(Self::to_time_string, js_string!("toTimeString"), 0)
.method(Self::value_of, js_string!("valueOf"), 0)
.property(
js_string!("toGMTString"),
to_utc_string.clone(),
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
js_string!("toUTCString"),
to_utc_string,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
JsSymbol::to_primitive(),
to_primitive,
Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
}
impl BuiltInObject for Date {
const NAME: JsString = StaticJsStrings::DATE;
}
impl BuiltInConstructor for Date {
const LENGTH: usize = 7;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::date;
/// [`Date ( ...values )`][spec]
///
/// - When called as a function, returns a string displaying the current time in the UTC timezone.
/// - When called as a constructor, it returns a new `Date` object from the provided arguments.
/// The [MDN documentation][mdn] has a more extensive explanation on the usages and return
/// values for all possible arguments.
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. If NewTarget is undefined, then
if new_target.is_undefined() {
// a. Let now be the time value (UTC) identifying the current time.
let now = context.host_hooks().utc_now();
// b. Return ToDateString(now).
return Ok(JsValue::from(to_date_string_t(
now as f64,
context.host_hooks(),
)));
}
// 2. Let numberOfArgs be the number of elements in values.
let dv = match args {
// 3. If numberOfArgs = 0, then
[] => {
// a. Let dv be the time value (UTC) identifying the current time.
Self::utc_now(context.host_hooks())
}
// 4. Else if numberOfArgs = 1, then
// a. Let value be values[0].
[value] => {
// b. If value is an Object and value has a [[DateValue]] internal slot, then
let tv = if let Some(date) =
value.as_object().and_then(JsObject::downcast_ref::<Self>)
{
// i. Let tv be value.[[DateValue]].
date.0
}
// c. Else,
else {
// i. Let v be ? ToPrimitive(value).
let v = value.to_primitive(context, PreferredType::Default)?;
// ii. If v is a String, then
if let Some(v) = v.as_string() {
// 1. Assert: The next step never returns an abrupt completion because v is a String.
// 2. Let tv be the result of parsing v as a date, in exactly the same manner as for the parse method (21.4.3.2).
let tv = parse_date(v, context.host_hooks());
if let Some(tv) = tv {
tv as f64
} else {
f64::NAN
}
}
// iii. Else,
else {
// 1. Let tv be ? ToNumber(v).
v.to_number(context)?
}
};
// d. Let dv be TimeClip(tv).
Self(time_clip(tv))
}
// 5. Else,
_ => {
// Separating this into its own function to simplify the logic.
//let dt = Self::construct_date(args, context)?
// .and_then(|dt| context.host_hooks().local_from_naive_local(dt).earliest());
//Self(dt.map(|dt| dt.timestamp_millis()))
// a. Assert: numberOfArgs ≥ 2.
// b. Let y be ? ToNumber(values[0]).
let y = args.get_or_undefined(0).to_number(context)?;
// c. Let m be ? ToNumber(values[1]).
let m = args.get_or_undefined(1).to_number(context)?;
// d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
let dt = args.get(2).map_or(Ok(1.0), |n| n.to_number(context))?;
// e. If numberOfArgs > 3, let h be ? ToNumber(values[3]); else let h be +0𝔽.
let h = args.get(3).map_or(Ok(0.0), |n| n.to_number(context))?;
// f. If numberOfArgs > 4, let min be ? ToNumber(values[4]); else let min be +0𝔽.
let min = args.get(4).map_or(Ok(0.0), |n| n.to_number(context))?;
// g. If numberOfArgs > 5, let s be ? ToNumber(values[5]); else let s be +0𝔽.
let s = args.get(5).map_or(Ok(0.0), |n| n.to_number(context))?;
// h. If numberOfArgs > 6, let milli be ? ToNumber(values[6]); else let milli be +0𝔽.
let milli = args.get(6).map_or(Ok(0.0), |n| n.to_number(context))?;
// i. Let yr be MakeFullYear(y).
let yr = make_full_year(y);
// j. Let finalDate be MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)).
let final_date = make_date(make_day(yr, m, dt), make_time(h, min, s, milli));
// k. Let dv be TimeClip(UTC(finalDate)).
Self(time_clip(utc_t(final_date, context.host_hooks())))
}
};
// 6. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »).
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::date, context)?;
// 7. Set O.[[DateValue]] to dv.
let obj =
JsObject::from_proto_and_data_with_shared_shape(context.root_shape(), prototype, dv);
// 8. Return O.
Ok(obj.into())
}
}
impl Date {
/// `Date.now()`
///
/// The static `Date.now()` method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.now
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn now(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::new(context.host_hooks().utc_now()))
}
/// `Date.parse()`
///
/// The `Date.parse()` method parses a string representation of a date, and returns the number of milliseconds since
/// January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date
/// values.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.parse
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
pub(crate) fn parse(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let date = args.get_or_undefined(0).to_string(context)?;
Ok(parse_date(&date, context.host_hooks()).map_or(JsValue::from(f64::NAN), JsValue::from))
}
/// `Date.UTC()`
///
/// The `Date.UTC()` method accepts parameters similar to the `Date` constructor, but treats them as UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.utc
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
pub(crate) fn utc(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let y be ? ToNumber(year).
let y = args.get_or_undefined(0).to_number(context)?;
// 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
let m = args
.get(1)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
let dt = args
.get(2)
.map_or(Ok(1f64), |value| value.to_number(context))?;
// 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
let h = args
.get(3)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
let min = args
.get(4)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
let s = args
.get(5)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
let milli = args
.get(6)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 8. Let yr be MakeFullYear(y).
let yr = make_full_year(y);
// 9. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
Ok(JsValue::from(time_clip(make_date(
make_day(yr, m, dt),
make_time(h, min, s, milli),
))))
}
/// [`Date.prototype.getDate ( )`][local] and
/// [`Date.prototype.getUTCDate ( )`][utc].
///
/// The `getDate()` method returns the day of the month for the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getdate
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcdate
pub(crate) fn get_date<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return DateFromTime(LocalTime(t)).
Ok(JsValue::from(date_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return DateFromTime(t).
Ok(JsValue::from(date_from_time(t)))
}
}
/// [`Date.prototype.getDay ( )`][local] and
/// [`Date.prototype.getUTCDay ( )`][utc].
///
/// The `getDay()` method returns the day of the week for the specified date, where 0 represents
/// Sunday.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getday
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcday
pub(crate) fn get_day<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return WeekDay(LocalTime(t)).
Ok(JsValue::from(week_day(local_time(t, context.host_hooks()))))
} else {
// 5. Return WeekDay(t).
Ok(JsValue::from(week_day(t)))
}
}
/// [`Date.prototype.getYear()`][spec].
///
/// The `getYear()` method returns the year in the specified date according to local time.
/// Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used
/// and has been replaced by the `getFullYear()` method.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear
pub(crate) fn get_year(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
// 5. Return YearFromTime(LocalTime(t)) - 1900𝔽.
Ok(JsValue::from(
year_from_time(local_time(t, context.host_hooks())) - 1900,
))
}
/// [`Date.prototype.getFullYear ( )`][local] and
/// [`Date.prototype.getUTCFullYear ( )`][utc].
///
/// The `getFullYear()` method returns the year of the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getfullyear
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcfullyear
pub(crate) fn get_full_year<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return YearFromTime(LocalTime(t)).
Ok(JsValue::from(year_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return YearFromTime(t).
Ok(JsValue::from(year_from_time(t)))
}
}
/// [`Date.prototype.getHours ( )`][local] and
/// [`Date.prototype.getUTCHours ( )`][utc].
///
/// The `getHours()` method returns the hour for the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.gethours
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutchours
pub(crate) fn get_hours<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return HourFromTime(LocalTime(t)).
Ok(JsValue::from(hour_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return HourFromTime(t).
Ok(JsValue::from(hour_from_time(t)))
}
}
/// [`Date.prototype.getMilliseconds ( )`][local] and
/// [`Date.prototype.getUTCMilliseconds ( )`][utc].
///
/// The `getMilliseconds()` method returns the milliseconds in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getmilliseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcmilliseconds
pub(crate) fn get_milliseconds<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return msFromTime(LocalTime(t)).
Ok(JsValue::from(ms_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return msFromTime(t).
Ok(JsValue::from(ms_from_time(t)))
}
}
/// [`Date.prototype.getMinutes ( )`][local] and
/// [`Date.prototype.getUTCMinutes ( )`][utc].
///
/// The `getMinutes()` method returns the minutes in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getminutes
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcminutes
pub(crate) fn get_minutes<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return MinFromTime(LocalTime(t)).
Ok(JsValue::from(min_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return MinFromTime(t).
Ok(JsValue::from(min_from_time(t)))
}
}
/// [`Date.prototype.getMonth ( )`][local] and
/// [`Date.prototype.getUTCMonth ( )`][utc].
///
/// The `getMonth()` method returns the month in the specified date, as a zero-based value
/// (where zero indicates the first month of the year).
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getmonth
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcmonth
pub(crate) fn get_month<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return MonthFromTime(LocalTime(t)).
Ok(JsValue::from(month_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return MonthFromTime(t).
Ok(JsValue::from(month_from_time(t)))
}
}
/// [`Date.prototype.getSeconds ( )`][local] and
/// [`Date.prototype.getUTCSeconds ( )`][utc].
///
/// The `getSeconds()` method returns the seconds in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcseconds
pub(crate) fn get_seconds<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 5. Return SecFromTime(LocalTime(t)).
Ok(JsValue::from(sec_from_time(local_time(
t,
context.host_hooks(),
))))
} else {
// 5. Return SecFromTime(t).
Ok(JsValue::from(sec_from_time(t)))
}
}
/// `Date.prototype.getTime()`.
///
/// The `getTime()` method returns the number of milliseconds since the Unix Epoch.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.gettime
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
pub(crate) fn get_time(
this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Return dateObject.[[DateValue]].
Ok(this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0
.into())
}
/// `Date.prototype.getTimeZoneOffset()`.
///
/// The `getTimezoneOffset()` method returns the time zone difference, in minutes, from current locale (host system
/// settings) to UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.gettimezoneoffset
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
pub(crate) fn get_timezone_offset(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
// 5. Return (t - LocalTime(t)) / msPerMinute.
Ok(JsValue::from(
(t - local_time(t, context.host_hooks())) / MS_PER_MINUTE,
))
}
/// [`Date.prototype.setDate ( date )`][local] and
/// [`Date.prototype.setUTCDate ( date )`][utc].
///
/// The `setDate()` method sets the day of the `Date` object relative to the beginning of the
/// currently set month.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setdate
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcdate
pub(crate) fn set_date<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Let dt be ? ToNumber(date).
let dt = args.get_or_undefined(0).to_number(context)?;
// 5. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 6. Set t to LocalTime(t).
t = local_time(t, context.host_hooks());
}
// 7. Let newDate be MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)).
let new_date = make_date(
make_day(year_from_time(t).into(), month_from_time(t).into(), dt),
time_within_day(t),
);
let u = if LOCAL {
// 8. Let u be TimeClip(UTC(newDate)).
time_clip(utc_t(new_date, context.host_hooks()))
} else {
// 8. Let v be TimeClip(newDate).
time_clip(new_date)
};
// 9. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 10. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setFullYear ( year [ , month [ , date ] ] )`][local] and
/// [Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )][utc].
///
/// The `setFullYear()` method sets the full year for a specified date and returns the new
/// timestamp.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setfullyear
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcfullyear
pub(crate) fn set_full_year<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let t = date_object.0;
let t = if LOCAL {
// 5. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
if t.is_nan() {
0.0
} else {
local_time(t, context.host_hooks())
}
} else {
// 4. If t is NaN, set t to +0𝔽.
if t.is_nan() {
0.0
} else {
t
}
};
// 4. Let y be ? ToNumber(year).
let y = args.get_or_undefined(0).to_number(context)?;
// 6. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month).
let m = if let Some(month) = args.get(1) {
month.to_number(context)?
} else {
month_from_time(t).into()
};
// 7. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date).
let dt = if let Some(date) = args.get(2) {
date.to_number(context)?
} else {
date_from_time(t).into()
};
// 8. Let newDate be MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)).
let new_date = make_date(make_day(y, m, dt), time_within_day(t));
let u = if LOCAL {
// 9. Let u be TimeClip(UTC(newDate)).
time_clip(utc_t(new_date, context.host_hooks()))
} else {
// 9. Let u be TimeClip(newDate).
time_clip(new_date)
};
// 10. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 11. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )`][local] and
/// [`Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )`][utc].
///
/// The `setHours()` method sets the hours for a specified date, and returns the number
/// of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the
/// updated `Date` instance.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.sethours
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutchours
#[allow(clippy::many_single_char_names)]
pub(crate) fn set_hours<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Let h be ? ToNumber(hour).
let h = args.get_or_undefined(0).to_number(context)?;
// 5. If min is present, let m be ? ToNumber(min).
let m = args.get(1).map(|v| v.to_number(context)).transpose()?;
// 6. If sec is present, let s be ? ToNumber(sec).
let s = args.get(2).map(|v| v.to_number(context)).transpose()?;
// 7. If ms is present, let milli be ? ToNumber(ms).
let milli = args.get(3).map(|v| v.to_number(context)).transpose()?;
// 8. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 9. Set t to LocalTime(t).
t = local_time(t, context.host_hooks());
}
// 10. If min is not present, let m be MinFromTime(t).
let m: f64 = m.unwrap_or_else(|| min_from_time(t).into());
// 11. If sec is not present, let s be SecFromTime(t).
let s = s.unwrap_or_else(|| sec_from_time(t).into());
// 12. If ms is not present, let milli be msFromTime(t).
let milli = milli.unwrap_or_else(|| ms_from_time(t).into());
// 13. Let date be MakeDate(Day(t), MakeTime(h, m, s, milli)).
let date = make_date(day(t), make_time(h, m, s, milli));
let u = if LOCAL {
// 14. Let u be TimeClip(UTC(date)).
time_clip(utc_t(date, context.host_hooks()))
} else {
// 14. Let u be TimeClip(date).
time_clip(date)
};
// 15. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 16. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setMilliseconds ( ms )`[local] and
/// [`Date.prototype.setUTCMilliseconds ( ms )`][utc].
///
/// The `setMilliseconds()` method sets the milliseconds for a specified date according to local time.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setmilliseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcmilliseconds
pub(crate) fn set_milliseconds<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Set ms to ? ToNumber(ms).
let ms = args.get_or_undefined(0).to_number(context)?;
// 5. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 6. Set t to LocalTime(t).
t = local_time(t, context.host_hooks());
}
// 7. Let time be MakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), ms).
let time = make_time(
hour_from_time(t).into(),
min_from_time(t).into(),
sec_from_time(t).into(),
ms,
);
let u = if LOCAL {
// 8. Let u be TimeClip(UTC(MakeDate(Day(t), time))).
time_clip(utc_t(make_date(day(t), time), context.host_hooks()))
} else {
// 8. Let u be TimeClip(MakeDate(Day(t), time)).
time_clip(make_date(day(t), time))
};
// 9. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 10. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )`][local] and
/// [`Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )`][utc].
///
/// The `setMinutes()` method sets the minutes for a specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setminutes
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcminutes
pub(crate) fn set_minutes<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Let m be ? ToNumber(min).
let m = args.get_or_undefined(0).to_number(context)?;
// 5. If sec is present, let s be ? ToNumber(sec).
let s = args.get(1).map(|v| v.to_number(context)).transpose()?;
// 6. If ms is present, let milli be ? ToNumber(ms).
let milli = args.get(2).map(|v| v.to_number(context)).transpose()?;
// 7. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
if LOCAL {
// 8. Set t to LocalTime(t).
t = local_time(t, context.host_hooks());
}
// 9. If sec is not present, let s be SecFromTime(t).
let s = s.unwrap_or_else(|| sec_from_time(t).into());
// 10. If ms is not present, let milli be msFromTime(t).
let milli = milli.unwrap_or_else(|| ms_from_time(t).into());
// 11. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli)).
let date = make_date(day(t), make_time(hour_from_time(t).into(), m, s, milli));
let u = if LOCAL {
// 12. Let u be TimeClip(UTC(date)).
time_clip(utc_t(date, context.host_hooks()))
} else {
// 12. Let u be TimeClip(date).
time_clip(date)
};
// 13. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 14. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setMonth ( month [ , date ] )`][local] and
/// [`Date.prototype.setUTCMonth ( month [ , date ] )`][utc].
///
/// The `setMonth()` method sets the month for a specified date according to the currently set
/// year.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setmonth
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcmonth
pub(crate) fn set_month<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Let m be ? ToNumber(month).
let m = args.get_or_undefined(0).to_number(context)?;
// 5. If date is present, let dt be ? ToNumber(date).
let dt = args.get(1).map(|v| v.to_number(context)).transpose()?;
// 6. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
// 7. Set t to LocalTime(t).
if LOCAL {
t = local_time(t, context.host_hooks());
}
// 8. If date is not present, let dt be DateFromTime(t).
let dt = dt.unwrap_or_else(|| date_from_time(t).into());
// 9. Let newDate be MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)).
let new_date = make_date(
make_day(year_from_time(t).into(), m, dt),
time_within_day(t),
);
let u = if LOCAL {
// 10. Let u be TimeClip(UTC(newDate)).
time_clip(utc_t(new_date, context.host_hooks()))
} else {
// 10. Let u be TimeClip(newDate).
time_clip(new_date)
};
// 11. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 12. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setSeconds ( sec [ , ms ] )`[local] and
/// [`Date.prototype.setUTCSeconds ( sec [ , ms ] )`][utc].
///
/// The `setSeconds()` method sets the seconds for a specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcseconds
pub(crate) fn set_seconds<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date_object.0;
// 4. Let s be ? ToNumber(sec).
let s = args.get_or_undefined(0).to_number(context)?;
// 5. If ms is present, let milli be ? ToNumber(ms).
let milli = args.get(1).map(|v| v.to_number(context)).transpose()?;
// 6. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
};
// 7. Set t to LocalTime(t).
if LOCAL {
t = local_time(t, context.host_hooks());
}
// 8. If ms is not present, let milli be msFromTime(t).
let milli = milli.unwrap_or_else(|| ms_from_time(t).into());
// 9. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli)).
let date = make_date(
day(t),
make_time(hour_from_time(t).into(), min_from_time(t).into(), s, milli),
);
let u = if LOCAL {
// 10. Let u be TimeClip(UTC(date)).
time_clip(utc_t(date, context.host_hooks()))
} else {
// 10. Let u be TimeClip(date).
time_clip(date)
};
// 11. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 12. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setYear()`][spec].
///
/// The `setYear()` method sets the year for a specified date according to local time.
///
/// # Note
///
/// The [`Self::set_full_year`] method is preferred for nearly all purposes, because it avoids
/// the “year 2000 problem.”
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setYear
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setyear
pub(crate) fn set_year(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let t = date_object.0;
// 4. Let y be ? ToNumber(year).
let y = args.get_or_undefined(0).to_number(context)?;
// 5. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
let t = if t.is_nan() {
0.0
} else {
local_time(t, context.host_hooks())
};
// 6. Let yyyy be MakeFullYear(y).
let yyyy = make_full_year(y);
// 7. Let d be MakeDay(yyyy, MonthFromTime(t), DateFromTime(t)).
let d = make_day(yyyy, month_from_time(t).into(), date_from_time(t).into());
// 8. Let date be MakeDate(d, TimeWithinDay(t)).
let date = make_date(d, time_within_day(t));
// 9. Let u be TimeClip(UTC(date)).
let u = time_clip(utc_t(date, context.host_hooks()));
// 10. Set dateObject.[[DateValue]] to u.
date_object.0 = u;
// 11. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setTime()`][spec].
///
/// The `setTime()` method sets the Date object to the time represented by a number of milliseconds
/// since January 1, 1970, 00:00:00 UTC.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.settime
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setTime
pub(crate) fn set_time(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let mut date_object = this
.as_object()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be ? ToNumber(time).
let t = args.get_or_undefined(0).to_number(context)?;
// 4. Let v be TimeClip(t).
let v = time_clip(t);
// 5. Set dateObject.[[DateValue]] to v.
date_object.0 = v;
// 6. Return v.
Ok(JsValue::from(v))
}
/// [`Date.prototype.toDateString()`][spec].
///
/// The `toDateString()` method returns the date portion of a Date object in English.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.todatestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
pub(crate) fn to_date_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let tv be dateObject.[[DateValue]].
let tv = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If tv is NaN, return "Invalid Date".
if tv.is_nan() {
return Ok(js_string!("Invalid Date").into());
};
// 5. Let t be LocalTime(tv).
let t = local_time(tv, context.host_hooks());
// 6. Return DateString(t).
Ok(JsValue::from(date_string(t)))
}
/// [`Date.prototype.toISOString()`][spec].
///
/// The `toISOString()` method returns a string in simplified extended ISO format
/// ([ISO 8601][iso8601]).
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [iso8601]: http://en.wikipedia.org/wiki/ISO_8601
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.toisostring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
pub(crate) fn to_iso_string(
this: &JsValue,
_: &[JsValue],
_: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let tv be dateObject.[[DateValue]].
let tv = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If tv is not finite, throw a RangeError exception.
if !tv.is_finite() {
return Err(JsNativeError::range()
.with_message("Invalid time value")
.into());
}
// 5. If tv corresponds with a year that cannot be represented in the Date Time String Format, throw a RangeError exception.
// 6. Return a String representation of tv in the Date Time String Format on the UTC time scale,
// including all format elements and the UTC offset representation "Z".
let year = year_from_time(tv);
let year = if year.is_positive() && year >= 10000 {
js_string!(utf16!("+"), &pad_six(year.unsigned_abs()))
} else if year.is_positive() {
JsString::from(&pad_four(year.unsigned_abs()))
} else {
js_string!(utf16!("-"), &pad_six(year.unsigned_abs()))
};
let month = pad_two(month_from_time(tv) + 1);
let day = pad_two(date_from_time(tv));
let hour = pad_two(hour_from_time(tv));
let minute = pad_two(min_from_time(tv));
let second = pad_two(sec_from_time(tv));
let millisecond = pad_three(ms_from_time(tv));
Ok(JsValue::from(js_string!(
&year,
utf16!("-"),
&month,
utf16!("-"),
&day,
utf16!("T"),
&hour,
utf16!(":"),
&minute,
utf16!(":"),
&second,
utf16!("."),
&millisecond,
utf16!("Z")
)))
}
/// [`Date.prototype.toJSON()`][spec].
///
/// The `toJSON()` method returns a string representation of the `Date` object.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.tojson
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
pub(crate) fn to_json(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be ? ToObject(this value).
let o = this.to_object(context)?;
// 2. Let tv be ? ToPrimitive(O, number).
let tv = this.to_primitive(context, PreferredType::Number)?;
// 3. If Type(tv) is Number and tv is not finite, return null.
if tv.as_number().map(f64::is_finite) == Some(false) {
return Ok(JsValue::null());
}
// 4. Return ? Invoke(O, "toISOString").
let func = o.get(utf16!("toISOString"), context)?;
func.call(this, &[], context)
}
/// [`Date.prototype.toLocaleDateString()`][spec].
///
/// The `toLocaleDateString()` method returns the date portion of the given Date instance according
/// to language-specific conventions.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.tolocaledatestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
pub(crate) fn to_locale_date_string(
_this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
Err(JsError::from_opaque(JsValue::new(js_string!(
"Function Unimplemented"
))))
}
/// [`Date.prototype.toLocaleString()`][spec].
///
/// The `toLocaleString()` method returns a string representing the specified Date object.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.tolocalestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
pub(crate) fn to_locale_string(
_this: &JsValue,
_: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
Err(JsError::from_opaque(JsValue::new(js_string!(
"Function Unimplemented]"
))))
}
/// [`Date.prototype.toLocaleTimeString()`][spec].
///
/// The `toLocaleTimeString()` method returns the time portion of a Date object in human readable
/// form in American English.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.tolocaletimestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
pub(crate) fn to_locale_time_string(
_this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
Err(JsError::from_opaque(JsValue::new(js_string!(
"Function Unimplemented]"
))))
}
/// [`Date.prototype.toString()`][spec].
///
/// The `toString()` method returns a string representing the specified Date object.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.tostring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
pub(crate) fn to_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let tv be dateObject.[[DateValue]].
let tv = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. Return ToDateString(tv).
Ok(JsValue::from(to_date_string_t(tv, context.host_hooks())))
}
/// [`Date.prototype.toTimeString()`][spec].
///
/// The `toTimeString()` method returns the time portion of a Date object in human readable form
/// in American English.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.totimestring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString
pub(crate) fn to_time_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let tv be dateObject.[[DateValue]].
let tv = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If tv is NaN, return "Invalid Date".
if tv.is_nan() {
return Ok(js_string!("Invalid Date").into());
}
// 5. Let t be LocalTime(tv).
let t = local_time(tv, context.host_hooks());
// 6. Return the string-concatenation of TimeString(t) and TimeZoneString(tv).
Ok(JsValue::from(js_string!(
&time_string(t),
&time_zone_string(t, context.host_hooks())
)))
}
/// [`Date.prototype.toUTCString()`][spec].
///
/// The `toUTCString()` method returns a string representing the specified Date object.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.toutcstring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
pub(crate) fn to_utc_string(
this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let tv be dateObject.[[DateValue]].
let tv = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If tv is NaN, return "Invalid Date".
if tv.is_nan() {
return Ok(js_string!("Invalid Date").into());
}
// 5. Let weekday be the Name of the entry in Table 63 with the Number WeekDay(tv).
let weekday = match week_day(tv) {
0 => utf16!("Sun"),
1 => utf16!("Mon"),
2 => utf16!("Tue"),
3 => utf16!("Wed"),
4 => utf16!("Thu"),
5 => utf16!("Fri"),
6 => utf16!("Sat"),
_ => unreachable!(),
};
// 6. Let month be the Name of the entry in Table 64 with the Number MonthFromTime(tv).
let month = match month_from_time(tv) {
0 => utf16!("Jan"),
1 => utf16!("Feb"),
2 => utf16!("Mar"),
3 => utf16!("Apr"),
4 => utf16!("May"),
5 => utf16!("Jun"),
6 => utf16!("Jul"),
7 => utf16!("Aug"),
8 => utf16!("Sep"),
9 => utf16!("Oct"),
10 => utf16!("Nov"),
11 => utf16!("Dec"),
_ => unreachable!(),
};
// 7. Let day be ToZeroPaddedDecimalString(ℝ(DateFromTime(tv)), 2).
let day = pad_two(date_from_time(tv));
// 8. Let yv be YearFromTime(tv).
let yv = year_from_time(tv);
// 9. If yv is +0𝔽 or yv > +0𝔽, let yearSign be the empty String; otherwise, let yearSign be "-".
let year_sign = if yv >= 0 { utf16!("") } else { utf16!("-") };
// 10. Let paddedYear be ToZeroPaddedDecimalString(abs(ℝ(yv)), 4).
let yv = yv.unsigned_abs();
let padded_year = if yv >= 100_000 {
js_string!(&pad_six(yv))
} else if yv >= 10000 {
js_string!(&pad_five(yv))
} else {
js_string!(&pad_four(yv))
};
// 11. Return the string-concatenation of
// weekday,
// ",",
// the code unit 0x0020 (SPACE),
// day,
// the code unit 0x0020 (SPACE),
// month,
// the code unit 0x0020 (SPACE),
// yearSign,
// paddedYear,
// the code unit 0x0020 (SPACE),
// and TimeString(tv).
Ok(JsValue::from(js_string!(
weekday,
utf16!(","),
utf16!(" "),
&day,
utf16!(" "),
month,
utf16!(" "),
year_sign,
&padded_year,
utf16!(" "),
&time_string(tv)
)))
}
/// [`Date.prototype.valueOf()`][spec].
///
/// The `valueOf()` method returns the primitive value of a `Date` object.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.valueof
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf
pub(crate) fn value_of(
this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Return dateObject.[[DateValue]].
Ok(this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0
.into())
}
/// [`Date.prototype [ @@toPrimitive ] ( hint )`][spec].
///
/// The <code>\[@@toPrimitive\]()</code> method converts a Date object to a primitive value.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype-@@toprimitive
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive
pub(crate) fn to_primitive(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be the this value.
// 2. If Type(O) is not Object, throw a TypeError exception.
let o = this.as_object().ok_or_else(|| {
JsNativeError::typ().with_message("Date.prototype[@@toPrimitive] called on non object")
})?;
let hint = args.get_or_undefined(0);
let try_first = match hint.as_string() {
// 3. If hint is "string" or "default", then
// a. Let tryFirst be string.
Some(string) if string == utf16!("string") || string == utf16!("default") => {
PreferredType::String
}
// 4. Else if hint is "number", then
// a. Let tryFirst be number.
Some(number) if number == utf16!("number") => PreferredType::Number,
// 5. Else, throw a TypeError exception.
_ => {
return Err(JsNativeError::typ()
.with_message("Date.prototype[@@toPrimitive] called with invalid hint")
.into())
}
};
// 6. Return ? OrdinaryToPrimitive(O, tryFirst).
o.ordinary_to_primitive(context, try_first)
}
}