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 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
#[cfg(test)]
mod tests;
use crate::{
builtins::BuiltIn,
context::StandardObjects,
gc::{empty_trace, Finalize, Trace},
object::{internal_methods::get_prototype_from_constructor, ConstructorBuilder, ObjectData},
property::Attribute,
symbol::WellKnownSymbols,
value::{JsValue, PreferredType},
BoaProfiler, Context, JsResult, JsString,
};
use chrono::{prelude::*, Duration, LocalResult};
use std::fmt::Display;
use super::JsArgs;
/// The number of nanoseconds in a millisecond.
const NANOS_PER_MS: i64 = 1_000_000;
/// The number of milliseconds in an hour.
const MILLIS_PER_HOUR: i64 = 3_600_000;
/// The number of milliseconds in a minute.
const MILLIS_PER_MINUTE: i64 = 60_000;
/// The number of milliseconds in a second.
const MILLIS_PER_SECOND: i64 = 1000;
#[inline]
fn is_zero_or_normal_opt(value: Option<f64>) -> bool {
value
.map(|value| value == 0f64 || value.is_normal())
.unwrap_or(true)
}
macro_rules! check_normal_opt {
($($v:expr),+) => {
$(is_zero_or_normal_opt($v.into()) &&)+ true
};
}
#[inline]
fn ignore_ambiguity<T>(result: LocalResult<T>) -> Option<T> {
match result {
LocalResult::Ambiguous(v, _) => Some(v),
LocalResult::Single(v) => Some(v),
LocalResult::None => None,
}
}
macro_rules! getter_method {
($name:ident) => {{
fn get_value(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::new(this_time_value(this, context)?.$name()))
}
get_value
}};
(Self::$name:ident) => {{
fn get_value(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::new(Date::$name()))
}
get_value
}};
}
#[derive(Debug, Finalize, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date(Option<NaiveDateTime>);
impl Display for Date {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.to_local() {
Some(v) => write!(f, "{}", v.format("%a %b %d %Y %H:%M:%S GMT%:z")),
_ => write!(f, "Invalid Date"),
}
}
}
unsafe impl Trace for Date {
// Date is a stack value, it doesn't require tracing.
// only safe if `chrono` never implements `Trace` for `NaiveDateTime`
empty_trace!();
}
impl Default for Date {
fn default() -> Self {
Self(Some(Utc::now().naive_utc()))
}
}
impl BuiltIn for Date {
const NAME: &'static str = "Date";
fn attribute() -> Attribute {
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE
}
fn init(context: &mut Context) -> (&'static str, JsValue, Attribute) {
let _timer = BoaProfiler::global().start_event(Self::NAME, "init");
let date_object = ConstructorBuilder::new(context, Self::constructor)
.name(Self::NAME)
.length(Self::LENGTH)
.method(getter_method!(get_date), "getDate", 0)
.method(getter_method!(get_day), "getDay", 0)
.method(getter_method!(get_full_year), "getFullYear", 0)
.method(getter_method!(get_hours), "getHours", 0)
.method(getter_method!(get_milliseconds), "getMilliseconds", 0)
.method(getter_method!(get_minutes), "getMinutes", 0)
.method(getter_method!(get_month), "getMonth", 0)
.method(getter_method!(get_seconds), "getSeconds", 0)
.method(getter_method!(get_time), "getTime", 0)
.method(getter_method!(get_year), "getYear", 0)
.method(Self::get_timezone_offset, "getTimezoneOffset", 0)
.method(getter_method!(get_utc_date), "getUTCDate", 0)
.method(getter_method!(get_utc_day), "getUTCDay", 0)
.method(getter_method!(get_utc_full_year), "getUTCFullYear", 0)
.method(getter_method!(get_utc_hours), "getUTCHours", 0)
.method(
getter_method!(get_utc_milliseconds),
"getUTCMilliseconds",
0,
)
.method(getter_method!(get_utc_minutes), "getUTCMinutes", 0)
.method(getter_method!(get_utc_month), "getUTCMonth", 0)
.method(getter_method!(get_utc_seconds), "getUTCSeconds", 0)
.method(Self::set_date, "setDate", 1)
.method(Self::set_full_year, "setFullYear", 3)
.method(Self::set_hours, "setHours", 4)
.method(Self::set_milliseconds, "setMilliseconds", 1)
.method(Self::set_minutes, "setMinutes", 3)
.method(Self::set_month, "setMonth", 2)
.method(Self::set_seconds, "setSeconds", 2)
.method(Self::set_year, "setYear", 1)
.method(Self::set_time, "setTime", 1)
.method(Self::set_utc_date, "setUTCDate", 1)
.method(Self::set_utc_full_year, "setUTCFullYear", 3)
.method(Self::set_utc_hours, "setUTCHours", 4)
.method(Self::set_utc_milliseconds, "setUTCMilliseconds", 1)
.method(Self::set_utc_minutes, "setUTCMinutes", 3)
.method(Self::set_utc_month, "setUTCMonth", 2)
.method(Self::set_utc_seconds, "setUTCSeconds", 2)
.method(Self::to_date_string, "toDateString", 0)
.method(getter_method!(to_gmt_string), "toGMTString", 0)
.method(Self::to_iso_string, "toISOString", 0)
.method(Self::to_json, "toJSON", 1)
// Locale strings
.method(Self::to_string, "toString", 0)
.method(Self::to_time_string, "toTimeString", 0)
.method(getter_method!(to_utc_string), "toUTCString", 0)
.method(getter_method!(value_of), "valueOf", 0)
.method(
Self::to_primitive,
(WellKnownSymbols::to_primitive(), "[Symbol.toPrimitive]"),
1,
)
.static_method(Self::now, "now", 0)
.static_method(Self::parse, "parse", 1)
.static_method(Self::utc, "UTC", 7)
.build();
(Self::NAME, date_object.into(), Self::attribute())
}
}
impl Date {
/// The amount of arguments this function object takes.
pub(crate) const LENGTH: usize = 7;
/// Check if the time (number of milliseconds) is in the expected range.
/// Returns None if the time is not in the range, otherwise returns the time itself in option.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-timeclip
#[inline]
pub fn time_clip(time: f64) -> Option<f64> {
if time.abs() > 8.64e15 {
None
} else {
Some(time)
}
}
/// Converts the `Date` to a local `DateTime`.
///
/// If the `Date` is invalid (i.e. NAN), this function will return `None`.
#[inline]
pub fn to_local(self) -> Option<DateTime<Local>> {
self.0
.map(|utc| Local::now().timezone().from_utc_datetime(&utc))
}
/// Converts the `Date` to a UTC `DateTime`.
///
/// If the `Date` is invalid (i.e. NAN), this function will return `None`.
pub fn to_utc(self) -> Option<DateTime<Utc>> {
self.0
.map(|utc| Utc::now().timezone().from_utc_datetime(&utc))
}
/// Optionally sets the individual components of the `Date`.
///
/// Each component does not have to be within the range of valid values. For example, if `month` is too large
/// then `year` will be incremented by the required amount.
#[allow(clippy::too_many_arguments)]
pub fn set_components(
&mut self,
utc: bool,
year: Option<f64>,
month: Option<f64>,
day: Option<f64>,
hour: Option<f64>,
minute: Option<f64>,
second: Option<f64>,
millisecond: Option<f64>,
) {
#[inline]
fn num_days_in(year: i32, month: u32) -> Option<u32> {
let month = month + 1; // zero-based for calculations
Some(
NaiveDate::from_ymd_opt(
match month {
12 => year.checked_add(1)?,
_ => year,
},
match month {
12 => 1,
_ => month + 1,
},
1,
)?
.signed_duration_since(NaiveDate::from_ymd_opt(year, month, 1)?)
.num_days() as u32,
)
}
#[inline]
fn fix_month(year: i32, month: i32) -> Option<(i32, u32)> {
let year = year.checked_add(month / 12)?;
if month < 0 {
let year = year.checked_sub(1)?;
let month = (11 + (month + 1) % 12) as u32;
Some((year, month))
} else {
let month = (month % 12) as u32;
Some((year, month))
}
}
#[inline]
fn fix_day(mut year: i32, mut month: i32, mut day: i32) -> Option<(i32, u32, u32)> {
loop {
if day < 0 {
let (fixed_year, fixed_month) = fix_month(year, month.checked_sub(1)?)?;
year = fixed_year;
month = fixed_month as i32;
day += num_days_in(fixed_year, fixed_month)? as i32;
} else {
let (fixed_year, fixed_month) = fix_month(year, month)?;
let num_days = num_days_in(fixed_year, fixed_month)? as i32;
if day >= num_days {
day -= num_days;
month = month.checked_add(1)?;
} else {
break;
}
}
}
let (fixed_year, fixed_month) = fix_month(year, month)?;
Some((fixed_year, fixed_month, day as u32))
}
// If any of the args are infinity or NaN, return an invalid date.
if !check_normal_opt!(year, month, day, hour, minute, second, millisecond) {
self.0 = None;
return;
}
let naive = if utc {
self.to_utc().map(|dt| dt.naive_utc())
} else {
self.to_local().map(|dt| dt.naive_local())
};
self.0 = naive.and_then(|naive| {
let year = year.unwrap_or_else(|| naive.year() as f64) as i32;
let month = month.unwrap_or_else(|| naive.month0() as f64) as i32;
let day = (day.unwrap_or_else(|| naive.day() as f64) as i32).checked_sub(1)?;
let hour = hour.unwrap_or_else(|| naive.hour() as f64) as i64;
let minute = minute.unwrap_or_else(|| naive.minute() as f64) as i64;
let second = second.unwrap_or_else(|| naive.second() as f64) as i64;
let millisecond = millisecond
.unwrap_or_else(|| naive.nanosecond() as f64 / NANOS_PER_MS as f64)
as i64;
let (year, month, day) = fix_day(year, month, day)?;
let duration_hour = Duration::milliseconds(hour.checked_mul(MILLIS_PER_HOUR)?);
let duration_minute = Duration::milliseconds(minute.checked_mul(MILLIS_PER_MINUTE)?);
let duration_second = Duration::milliseconds(second.checked_mul(MILLIS_PER_SECOND)?);
let duration_milisecond = Duration::milliseconds(millisecond);
let duration = duration_hour
.checked_add(&duration_minute)?
.checked_add(&duration_second)?
.checked_add(&duration_milisecond)?;
NaiveDate::from_ymd_opt(year, month + 1, day + 1)
.and_then(|dt| dt.and_hms(0, 0, 0).checked_add_signed(duration))
.and_then(|dt| {
if utc {
Some(Utc.from_utc_datetime(&dt).naive_utc())
} else {
ignore_ambiguity(Local.from_local_datetime(&dt)).map(|dt| dt.naive_utc())
}
})
.filter(|dt| Self::time_clip(dt.timestamp_millis() as f64).is_some())
});
}
/// `Date()`
///
/// Creates a JavaScript `Date` instance that represents a single moment in time in a platform-independent format.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
pub(crate) fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
if new_target.is_undefined() {
Ok(Self::make_date_string())
} else {
let prototype = get_prototype_from_constructor(
new_target,
StandardObjects::object_object,
context,
)?;
let obj = context.construct_object();
obj.set_prototype_instance(prototype.into());
let this = obj.into();
if args.is_empty() {
Ok(Self::make_date_now(&this))
} else if args.len() == 1 {
Self::make_date_single(&this, args, context)
} else {
Self::make_date_multiple(&this, args, context)
}
}
}
/// `Date()`
///
/// The `Date()` function is used to create a string that represent the current date and time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
pub(crate) fn make_date_string() -> JsValue {
JsValue::new(Local::now().to_rfc3339())
}
/// `Date()`
///
/// The newly-created `Date` object represents the current date and time as of the time of instantiation.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
pub(crate) fn make_date_now(this: &JsValue) -> JsValue {
let date = Date::default();
this.set_data(ObjectData::date(date));
this.clone()
}
/// `Date(value)`
///
/// The newly-created `Date` object represents the value provided to the constructor.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
pub(crate) fn make_date_single(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let value = &args[0];
let tv = match this_time_value(value, context) {
Ok(dt) => dt.0,
_ => match value.to_primitive(context, PreferredType::Default)? {
JsValue::String(ref str) => match chrono::DateTime::parse_from_rfc3339(str) {
Ok(dt) => Some(dt.naive_utc()),
_ => None,
},
tv => {
let tv = tv.to_number(context)?;
if tv.is_nan() {
None
} else {
let secs = (tv / 1_000f64) as i64;
let nsecs = ((tv % 1_000f64) * 1_000_000f64) as u32;
NaiveDateTime::from_timestamp_opt(secs, nsecs)
}
}
},
};
let tv = tv.filter(|time| Self::time_clip(time.timestamp_millis() as f64).is_some());
let date = Date(tv);
this.set_data(ObjectData::date(date));
Ok(this.clone())
}
/// `Date(year, month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ])`
///
/// The newly-created `Date` object represents the date components provided to the constructor.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
pub(crate) fn make_date_multiple(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
let mut year = args[0].to_number(context)?;
let month = args[1].to_number(context)?;
let day = args
.get(2)
.map_or(Ok(1f64), |value| value.to_number(context))?;
let hour = args
.get(3)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let min = args
.get(4)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let sec = args
.get(5)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let milli = args
.get(6)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// If any of the args are infinity or NaN, return an invalid date.
if !check_normal_opt!(year, month, day, hour, min, sec, milli) {
let date = Date(None);
this.set_data(ObjectData::date(date));
return Ok(this.clone());
}
if (0.0..=99.0).contains(&year) {
year += 1900.0
}
let mut date = Self(
NaiveDateTime::from_timestamp_opt(0, 0)
.and_then(|local| ignore_ambiguity(Local.from_local_datetime(&local)))
.map(|local| local.naive_utc())
.filter(|time| Self::time_clip(time.timestamp_millis() as f64).is_some()),
);
date.set_components(
false,
Some(year),
Some(month),
Some(day),
Some(hour),
Some(min),
Some(sec),
Some(milli),
);
this.set_data(ObjectData::date(date));
Ok(this.clone())
}
/// `Date.prototype[@@toPrimitive]`
///
/// The [@@toPrimitive]() method converts a Date object to a primitive value.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
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 = if let Some(o) = this.as_object() {
o
} else {
return context.throw_type_error("Date.prototype[@@toPrimitive] called on non object");
};
let hint = args.get_or_undefined(0);
let try_first = match hint.as_string().map(|s| s.as_str()) {
// 3. If hint is "string" or "default", then
// a. Let tryFirst be string.
Some("string") | Some("default") => PreferredType::String,
// 4. Else if hint is "number", then
// a. Let tryFirst be number.
Some("number") => PreferredType::Number,
// 5. Else, throw a TypeError exception.
_ => {
return context
.throw_type_error("Date.prototype[@@toPrimitive] called with invalid hint")
}
};
// 6. Return ? OrdinaryToPrimitive(O, tryFirst).
o.ordinary_to_primitive(context, try_first)
}
/// `Date.prototype.getDate()`
///
/// The `getDate()` method returns the day of the month for the specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getdate
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDate
pub fn get_date(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.day() as f64)
}
/// `Date.prototype.getDay()`
///
/// The `getDay()` method returns the day of the week for the specified date according to local time, where 0
/// represents Sunday.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getday
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
pub fn get_day(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| {
let weekday = dt.weekday() as u32;
let weekday = (weekday + 1) % 7; // 0 represents Monday in Chrono
weekday as f64
})
}
/// `Date.prototype.getFullYear()`
///
/// The `getFullYear()` method returns the year of the specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getfullyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear
pub fn get_full_year(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.year() as f64)
}
/// `Date.prototype.getHours()`
///
/// The `getHours()` method returns the hour for the specified date, according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.gethours
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
pub fn get_hours(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.hour() as f64)
}
/// `Date.prototype.getMilliseconds()`
///
/// The `getMilliseconds()` method returns the milliseconds in the specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getmilliseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds
pub fn get_milliseconds(&self) -> f64 {
self.to_local()
.map_or(f64::NAN, |dt| dt.nanosecond() as f64 / NANOS_PER_MS as f64)
}
/// `Date.prototype.getMinutes()`
///
/// The `getMinutes()` method returns the minutes in the specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getminutes
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes
pub fn get_minutes(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.minute() as f64)
}
/// `Date.prototype.getMonth()`
///
/// The `getMonth()` method returns the month in the specified date according to local time, as a zero-based value
/// (where zero indicates the first month of the year).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getmonth
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
pub fn get_month(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.month0() as f64)
}
/// `Date.prototype.getSeconds()`
///
/// The `getSeconds()` method returns the seconds in the specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getSeconds
pub fn get_seconds(&self) -> f64 {
self.to_local().map_or(f64::NAN, |dt| dt.second() as f64)
}
/// `Date.prototype.getYear()`
///
/// 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:
/// - [ECMAScript reference][spec]
/// - [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 fn get_year(&self) -> f64 {
self.to_local()
.map_or(f64::NAN, |dt| dt.year() as f64 - 1900f64)
}
/// `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 fn get_time(&self) -> f64 {
self.to_utc()
.map_or(f64::NAN, |dt| dt.timestamp_millis() as f64)
}
/// `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
#[inline]
pub fn get_timezone_offset(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let t = this_time_value(this, context)?;
// 2. If t is NaN, return NaN.
if t.0.is_none() {
return Ok(JsValue::nan());
}
// 3. Return (t - LocalTime(t)) / msPerMinute.
Ok(JsValue::new(
-Local::now().offset().local_minus_utc() as f64 / 60f64,
))
}
/// `Date.prototype.getUTCDate()`
///
/// The `getUTCDate()` method returns the day (date) of the month in the specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcdate
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDate
pub fn get_utc_date(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.day() as f64)
}
/// `Date.prototype.getUTCDay()`
///
/// The `getUTCDay()` method returns the day of the week in the specified date according to universal time, where 0
/// represents Sunday.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcday
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCDay
pub fn get_utc_day(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| {
let weekday = dt.weekday() as u32;
let weekday = (weekday + 1) % 7; // 0 represents Monday in Chrono
weekday as f64
})
}
/// `Date.prototype.getUTCFullYear()`
///
/// The `getUTCFullYear()` method returns the year in the specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcfullyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear
pub fn get_utc_full_year(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.year() as f64)
}
/// `Date.prototype.getUTCHours()`
///
/// The `getUTCHours()` method returns the hours in the specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutchours
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
pub fn get_utc_hours(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.hour() as f64)
}
/// `Date.prototype.getUTCMilliseconds()`
///
/// The `getUTCMilliseconds()` method returns the milliseconds portion of the time object's value.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcmilliseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds
pub fn get_utc_milliseconds(&self) -> f64 {
self.to_utc()
.map_or(f64::NAN, |dt| dt.nanosecond() as f64 / NANOS_PER_MS as f64)
}
/// `Date.prototype.getUTCMinutes()`
///
/// The `getUTCMinutes()` method returns the minutes in the specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcminutes
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes
pub fn get_utc_minutes(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.minute() as f64)
}
/// `Date.prototype.getUTCMonth()`
///
/// The `getUTCMonth()` returns the month of the specified date according to universal time, as a zero-based value
/// (where zero indicates the first month of the year).
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcmonth
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth
pub fn get_utc_month(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.month0() as f64)
}
/// `Date.prototype.getUTCSeconds()`
///
/// The `getUTCSeconds()` method returns the seconds in the specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getutcseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds
pub fn get_utc_seconds(&self) -> f64 {
self.to_utc().map_or(f64::NAN, |dt| dt.second() as f64)
}
/// `Date.prototype.setDate()`
///
/// The `setDate()` method sets the day of the `Date` object relative to the beginning of the currently set
/// month.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setdate
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
pub fn set_date(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Let dt be ? ToNumber(date).
let dt = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. Let newDate be MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)).
t.set_components(false, None, None, Some(dt), None, None, None, None);
// 4. Let u be TimeClip(UTC(newDate)).
let u = t.get_time();
// 5. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 6. Return u.
Ok(u.into())
}
/// `Date.prototype.setFullYear()`
///
/// The `setFullYear()` method sets the full year for a specified date according to local time. Returns new
/// timestamp.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setfullyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear
pub fn set_full_year(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
if t.0.is_none() {
t.0 = NaiveDateTime::from_timestamp_opt(0, 0)
.and_then(|local| ignore_ambiguity(Local.from_local_datetime(&local)))
.map(|local| local.naive_utc())
.filter(|time| Self::time_clip(time.timestamp_millis() as f64).is_some());
}
// 3. Let y be ? ToNumber(year).
let y = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 4. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month).
let m = if let Some(m) = args.get(1) {
Some(m.to_number(context)?)
} else {
None
};
// 5. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date).
let dt = if let Some(dt) = args.get(2) {
Some(dt.to_number(context)?)
} else {
None
};
// 6. Let newDate be MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)).
t.set_components(false, Some(y), m, dt, None, None, None, None);
// 7. Let u be TimeClip(UTC(newDate)).
let u = t.get_time();
// 8. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 9. Return u.
Ok(u.into())
}
/// `Date.prototype.setHours()`
///
/// The `setHours()` method sets the hours for a specified date according to local time, and returns the number
/// of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date`
/// instance.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.sethours
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
pub fn set_hours(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Let h be ? ToNumber(hour).
let h = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If min is not present, let m be MinFromTime(t); otherwise, let m be ? ToNumber(min).
let m = if let Some(m) = args.get(1) {
Some(m.to_number(context)?)
} else {
None
};
// 4. If sec is not present, let s be SecFromTime(t); otherwise, let s be ? ToNumber(sec).
let sec = if let Some(sec) = args.get(2) {
Some(sec.to_number(context)?)
} else {
None
};
// 5. If ms is not present, let milli be msFromTime(t); otherwise, let milli be ? ToNumber(ms).
let milli = if let Some(milli) = args.get(3) {
Some(milli.to_number(context)?)
} else {
None
};
// 6. Let date be MakeDate(Day(t), MakeTime(h, m, s, milli)).
t.set_components(false, None, None, None, Some(h), m, sec, milli);
// 7. Let u be TimeClip(UTC(date)).
let u = t.get_time();
// 8. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 9. Return u.
Ok(u.into())
}
/// `Date.prototype.setMilliseconds()`
///
/// The `setMilliseconds()` method sets the milliseconds for a specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setmilliseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds
pub fn set_milliseconds(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Set ms to ? ToNumber(ms).
let ms = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. Let time be MakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), ms).
t.set_components(false, None, None, None, None, None, None, Some(ms));
// 4. Let u be TimeClip(UTC(MakeDate(Day(t), time))).
let u = t.get_time();
// 5. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 6. Return u.
Ok(u.into())
}
/// `Date.prototype.setMinutes()`
///
/// The `setMinutes()` method sets the minutes for a specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setminutes
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes
pub fn set_minutes(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Let m be ? ToNumber(min).
let m = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If sec is not present, let s be SecFromTime(t); otherwise, let s be ? ToNumber(sec).
let s = if let Some(s) = args.get(1) {
Some(s.to_number(context)?)
} else {
None
};
// 4. If ms is not present, let milli be msFromTime(t); otherwise, let milli be ? ToNumber(ms).
let milli = if let Some(milli) = args.get(2) {
Some(milli.to_number(context)?)
} else {
None
};
// 5. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli)).
t.set_components(false, None, None, None, None, Some(m), s, milli);
// 6. Let u be TimeClip(UTC(date)).
let u = t.get_time();
// 7. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 8. Return u.
Ok(u.into())
}
/// `Date.prototype.setMonth()`
///
/// The `setMonth()` method sets the month for a specified date according to the currently set year.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setmonth
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth
pub fn set_month(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Let m be ? ToNumber(month).
let m = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date).
let dt = if let Some(date) = args.get(1) {
Some(date.to_number(context)?)
} else {
None
};
// 4. Let newDate be MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)).
t.set_components(false, None, Some(m), dt, None, None, None, None);
// 5. Let u be TimeClip(UTC(newDate)).
let u = t.get_time();
// 6. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 7. Return u.
Ok(u.into())
}
/// `Date.prototype.setSeconds()`
///
/// The `setSeconds()` method sets the seconds for a specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setSeconds
pub fn set_seconds(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be LocalTime(? thisTimeValue(this value)).
let mut t = this_time_value(this, context)?;
// 2. Let s be ? ToNumber(sec).
let s = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If ms is not present, let milli be msFromTime(t); otherwise, let milli be ? ToNumber(ms).
let milli = if let Some(milli) = args.get(1) {
Some(milli.to_number(context)?)
} else {
None
};
// 4. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli)).
t.set_components(false, None, None, None, None, None, Some(s), milli);
// 5. Let u be TimeClip(UTC(date)).
let u = t.get_time();
// 6. Set the [[DateValue]] internal slot of this Date object to u.
this.set_data(ObjectData::date(t));
// 7. Return u.
Ok(u.into())
}
/// `Date.prototype.setYear()`
///
/// The `setYear()` method sets the year for a specified date according to local time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setYear
pub fn set_year(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
if t.0.is_none() {
t.0 = NaiveDateTime::from_timestamp_opt(0, 0)
.and_then(|local| ignore_ambiguity(Local.from_local_datetime(&local)))
.map(|local| local.naive_utc())
.filter(|time| Self::time_clip(time.timestamp_millis() as f64).is_some());
}
// 3. Let y be ? ToNumber(year).
let mut y = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 4. If y is NaN, then
if y.is_nan() {
// a. Set the [[DateValue]] internal slot of this Date object to NaN.
this.set_data(ObjectData::date(Date(None)));
// b. Return NaN.
return Ok(JsValue::nan());
}
// 5. Let yi be ! ToIntegerOrInfinity(y).
// 6. If 0 ≤ yi ≤ 99, let yyyy be 1900𝔽 + 𝔽(yi).
// 7. Else, let yyyy be y.
if (0f64..=99f64).contains(&y) {
y += 1900f64;
}
// 8. Let d be MakeDay(yyyy, MonthFromTime(t), DateFromTime(t)).
// 9. Let date be UTC(MakeDate(d, TimeWithinDay(t))).
t.set_components(false, Some(y), None, None, None, None, None, None);
// 10. Set the [[DateValue]] internal slot of this Date object to TimeClip(date).
this.set_data(ObjectData::date(t));
// 11. Return the value of the [[DateValue]] internal slot of this Date object.
Ok(t.get_time().into())
}
/// `Date.prototype.setTime()`
///
/// 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:
/// - [ECMAScript reference][spec]
/// - [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 fn set_time(this: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Perform ? thisTimeValue(this value).
this_time_value(this, context)?;
// 2. Let t be ? ToNumber(time).
let t = if let Some(t) = args.get(0) {
let t = t.to_number(context)?;
let seconds = (t / 1_000f64) as i64;
let nanoseconds = ((t % 1_000f64) * 1_000_000f64) as u32;
Date(
ignore_ambiguity(Local.timestamp_opt(seconds, nanoseconds))
.map(|dt| dt.naive_utc()),
)
} else {
Date(None)
};
// 3. Let v be TimeClip(t).
let v = t.get_time();
// 4. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 5. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCDate()`
///
/// The `setUTCDate()` method sets the day of the month for a specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcdate
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCDate
pub fn set_utc_date(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let dt be ? ToNumber(date).
let dt = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. Let newDate be MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)).
t.set_components(true, None, None, Some(dt), None, None, None, None);
// 4. Let v be TimeClip(newDate).
let v = t.get_time();
// 5. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 6. Return v.
Ok(v.into())
}
/// `Date.prototype.setFullYear()`
///
/// The `setFullYear()` method sets the full year for a specified date according to local time. Returns new
/// timestamp.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcfullyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear
pub fn set_utc_full_year(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. If t is NaN, set t to +0𝔽.
if t.0.is_none() {
t.0 = NaiveDateTime::from_timestamp_opt(0, 0)
.and_then(|local| ignore_ambiguity(Local.from_local_datetime(&local)))
.map(|local| local.naive_utc())
.filter(|time| Self::time_clip(time.timestamp_millis() as f64).is_some());
}
// 3. Let y be ? ToNumber(year).
let y = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 4. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month).
let m = if let Some(m) = args.get(1) {
Some(m.to_number(context)?)
} else {
None
};
// 5. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date).
let dt = if let Some(dt) = args.get(2) {
Some(dt.to_number(context)?)
} else {
None
};
// 6. Let newDate be MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)).
t.set_components(true, Some(y), m, dt, None, None, None, None);
// 7. Let v be TimeClip(newDate).
let v = t.get_time();
// 8. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 9. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCHours()`
///
/// The `setUTCHours()` method sets the hour for a specified date according to universal time, and returns the
/// number of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the updated `Date`
/// instance.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutchours
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours
pub fn set_utc_hours(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let h be ? ToNumber(hour).
let h = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If min is not present, let m be MinFromTime(t); otherwise, let m be ? ToNumber(min).
let m = if let Some(m) = args.get(1) {
Some(m.to_number(context)?)
} else {
None
};
// 4. If sec is not present, let s be SecFromTime(t); otherwise, let s be ? ToNumber(sec).
let sec = if let Some(s) = args.get(2) {
Some(s.to_number(context)?)
} else {
None
};
// 5. If ms is not present, let milli be msFromTime(t); otherwise, let milli be ? ToNumber(ms).
let ms = if let Some(ms) = args.get(3) {
Some(ms.to_number(context)?)
} else {
None
};
// 6. Let newDate be MakeDate(Day(t), MakeTime(h, m, s, milli)).
t.set_components(true, None, None, None, Some(h), m, sec, ms);
// 7. Let v be TimeClip(newDate).
let v = t.get_time();
// 8. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 9. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCMilliseconds()`
///
/// The `setUTCMilliseconds()` method sets the milliseconds for a specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcmilliseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds
pub fn set_utc_milliseconds(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let milli be ? ToNumber(ms).
let ms = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. Let time be MakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), milli).
t.set_components(true, None, None, None, None, None, None, Some(ms));
// 4. Let v be TimeClip(MakeDate(Day(t), time)).
let v = t.get_time();
// 5. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 6. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCMinutes()`
///
/// The `setUTCMinutes()` method sets the minutes for a specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcminutes
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes
pub fn set_utc_minutes(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let m be ? ToNumber(min).
let m = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If sec is not present, let s be SecFromTime(t).
// 4. Else,
let s = if let Some(s) = args.get(1) {
// a. Let s be ? ToNumber(sec).
Some(s.to_number(context)?)
} else {
None
};
// 5. If ms is not present, let milli be msFromTime(t).
// 6. Else,
let milli = if let Some(ms) = args.get(2) {
// a. Let milli be ? ToNumber(ms).
Some(ms.to_number(context)?)
} else {
None
};
// 7. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli)).
t.set_components(true, None, None, None, None, Some(m), s, milli);
// 8. Let v be TimeClip(date).
let v = t.get_time();
// 9. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 10. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCMonth()`
///
/// The `setUTCMonth()` method sets the month for a specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcmonth
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth
pub fn set_utc_month(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let m be ? ToNumber(month).
let m = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If date is not present, let dt be DateFromTime(t).
// 4. Else,
let dt = if let Some(dt) = args.get(1) {
// a. Let dt be ? ToNumber(date).
Some(dt.to_number(context)?)
} else {
None
};
// 5. Let newDate be MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)).
t.set_components(true, None, Some(m), dt, None, None, None, None);
// 6. Let v be TimeClip(newDate).
let v = t.get_time();
// 7. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 8. Return v.
Ok(v.into())
}
/// `Date.prototype.setUTCSeconds()`
///
/// The `setUTCSeconds()` method sets the seconds for a specified date according to universal time.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.setutcseconds
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds
pub fn set_utc_seconds(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let t be ? thisTimeValue(this value).
let mut t = this_time_value(this, context)?;
// 2. Let s be ? ToNumber(sec).
let s = args
.get(0)
.cloned()
.unwrap_or_default()
.to_number(context)?;
// 3. If ms is not present, let milli be msFromTime(t).
// 4. Else,
let milli = if let Some(milli) = args.get(1) {
// a. Let milli be ? ToNumber(ms).
Some(milli.to_number(context)?)
} else {
None
};
// 5. Let date be MakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli)).
t.set_components(true, None, None, None, None, None, Some(s), milli);
// 6. Let v be TimeClip(date).
let v = t.get_time();
// 7. Set the [[DateValue]] internal slot of this Date object to v.
this.set_data(ObjectData::date(t));
// 8. Return v.
Ok(v.into())
}
/// `Date.prototype.toDateString()`
///
/// The `toDateString()` method returns the date portion of a Date object in English.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
pub fn to_date_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be this Date object.
// 2. Let tv be ? thisTimeValue(O).
let tv = this_time_value(this, context)?;
// 3. If tv is NaN, return "Invalid Date".
// 4. Let t be LocalTime(tv).
// 5. Return DateString(t).
if let Some(t) = tv.0 {
Ok(t.format("%a %b %d %Y").to_string().into())
} else {
Ok(JsString::from("Invalid Date").into())
}
}
/// `Date.prototype.toGMTString()`
///
/// The `toGMTString()` method converts a date to a string, using Internet Greenwich Mean Time (GMT) conventions.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.togmtstring
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString
pub fn to_gmt_string(self) -> String {
self.to_utc_string()
}
/// `Date.prototype.toISOString()`
///
/// The `toISOString()` method returns a string in simplified extended ISO format (ISO 8601).
///
/// More information:
/// - [ISO 8601][iso8601]
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
pub fn to_iso_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
if let Some(t) = this_time_value(this, context)?.0 {
Ok(Utc::now()
.timezone()
.from_utc_datetime(&t)
.format("%Y-%m-%dT%H:%M:%S.%3fZ")
.to_string()
.into())
} else {
context.throw_range_error("Invalid time value")
}
}
/// `Date.prototype.toJSON()`
///
/// The `toJSON()` method returns a string representation of the `Date` object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
pub 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 let Some(number) = tv.as_number() {
if !number.is_finite() {
return Ok(JsValue::null());
}
}
// 4. Return ? Invoke(O, "toISOString").
if let Some(to_iso_string) = o.get_method(context, "toISOString")? {
to_iso_string.call(this, &[], context)
} else {
context.throw_type_error("toISOString in undefined")
}
}
/// `Date.prototype.toString()`
///
/// The toString() method returns a string representing the specified Date object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
pub fn to_string(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let tv be ? thisTimeValue(this value).
let tv = this_time_value(this, context)?;
// 2. Return ToDateString(tv).
if let Some(t) = tv.0 {
Ok(Local::now()
.timezone()
.from_utc_datetime(&t)
.format("%a %b %d %Y %H:%M:%S GMT%z")
.to_string()
.into())
} else {
Ok(JsString::from("Invalid Date").into())
}
}
/// `Date.prototype.toTimeString()`
///
/// The `toTimeString()` method returns the time portion of a Date object in human readable form in American
/// English.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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
#[allow(clippy::wrong_self_convention)]
pub fn to_time_string(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let O be this Date object.
// 2. Let tv be ? thisTimeValue(O).
let tv = this_time_value(this, context)?;
// 3. If tv is NaN, return "Invalid Date".
// 4. Let t be LocalTime(tv).
// 5. Return the string-concatenation of TimeString(t) and TimeZoneString(tv).
if let Some(t) = tv.0 {
Ok(Local::now()
.timezone()
.from_utc_datetime(&t)
.format("%H:%M:%S GMT%z")
.to_string()
.into())
} else {
Ok(JsString::from("Invalid Date").into())
}
}
/// `Date.prototype.toUTCString()`
///
/// The `toUTCString()` method returns a string representing the specified Date object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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 fn to_utc_string(self) -> String {
self.to_utc()
.map(|date_time| date_time.format("%a, %d %b %Y %H:%M:%S GMT").to_string())
.unwrap_or_else(|| "Invalid Date".to_string())
}
/// `Date.prototype.valueOf()`
///
/// The `valueOf()` method returns the primitive value of a `Date` object.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [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 fn value_of(&self) -> f64 {
self.get_time()
}
/// `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
pub(crate) fn now(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::new(Utc::now().timestamp_millis() as f64))
}
/// `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> {
// This method is implementation-defined and discouraged, so we just require the same format as the string
// constructor.
if args.is_empty() {
return Ok(JsValue::nan());
}
match DateTime::parse_from_rfc3339(&args[0].to_string(context)?) {
Ok(v) => Ok(JsValue::new(v.naive_utc().timestamp_millis() as f64)),
_ => Ok(JsValue::new(f64::NAN)),
}
}
/// `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> {
let year = args
.get(0)
.map_or(Ok(f64::NAN), |value| value.to_number(context))?;
let month = args
.get(1)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let day = args
.get(2)
.map_or(Ok(1f64), |value| value.to_number(context))?;
let hour = args
.get(3)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let min = args
.get(4)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let sec = args
.get(5)
.map_or(Ok(0f64), |value| value.to_number(context))?;
let milli = args
.get(6)
.map_or(Ok(0f64), |value| value.to_number(context))?;
if !check_normal_opt!(year, month, day, hour, min, sec, milli) {
return Ok(JsValue::nan());
}
let year = year as i32;
let month = month as u32;
let day = day as u32;
let hour = hour as u32;
let min = min as u32;
let sec = sec as u32;
let milli = milli as u32;
let year = if (0..=99).contains(&year) {
1900 + year
} else {
year
};
NaiveDate::from_ymd_opt(year, month + 1, day)
.and_then(|f| f.and_hms_milli_opt(hour, min, sec, milli))
.and_then(|f| Self::time_clip(f.timestamp_millis() as f64))
.map_or(Ok(JsValue::nan()), |time| Ok(JsValue::new(time)))
}
}
/// The abstract operation `thisTimeValue` takes argument value.
///
/// In following descriptions of functions that are properties of the Date prototype object, the phrase “this
/// Date object” refers to the object that is the this value for the invocation of the function. If the `Type` of
/// the this value is not `Object`, a `TypeError` exception is thrown. The phrase “this time value” within the
/// specification of a method refers to the result returned by calling the abstract operation `thisTimeValue` with
/// the this value of the method invocation passed as the argument.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-thistimevalue
#[inline]
pub fn this_time_value(value: &JsValue, context: &mut Context) -> JsResult<Date> {
if let JsValue::Object(ref object) = value {
if let Some(date) = object.borrow().as_date() {
return Ok(*date);
}
}
Err(context.construct_type_error("'this' is not a Date"))
}