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
#[cfg(test)] mod tests; use crate::{ builtins::BuiltIn, gc::{empty_trace, Finalize, Trace}, object::{ConstructorBuilder, ObjectData, PROTOTYPE}, property::Attribute, value::{PreferredType, Value}, BoaProfiler, Context, Result, }; use chrono::{prelude::*, Duration, LocalResult}; use std::fmt::Display; const NANOS_IN_MS: f64 = 1_000_000f64; #[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: &Value, _: &[Value], context: &mut Context) -> Result<Value> { Ok(Value::from(this_time_value(this, context)?.$name())) } get_value }}; (Self::$name:ident) => {{ fn get_value(_: &Value, _: &[Value], _: &mut Context) -> Result<Value> { Ok(Value::from(Date::$name())) } get_value }}; } macro_rules! setter_method { ($name:ident($($e:expr),* $(,)?)) => {{ fn set_value(this: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let mut result = this_time_value(this, context)?; result.$name( $( args .get($e) .and_then(|value| { value.to_numeric_number(context).map_or_else( |_| None, |value| { if value == 0f64 || value.is_normal() { Some(value) } else { None } }, ) }) ),* ); this.set_data(ObjectData::Date(result)); Ok(Value::from(result.get_time())) } set_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, Value, 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( getter_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(setter_method!(set_date(0)), "setDate", 1) .method(setter_method!(set_full_year(0, 1, 2)), "setFullYear", 1) .method(setter_method!(set_hours(0, 1, 2, 3)), "setHours", 1) .method(setter_method!(set_milliseconds(0)), "setMilliseconds", 1) .method(setter_method!(set_minutes(0, 1, 2)), "setMinutes", 1) .method(setter_method!(set_month(0, 1)), "setMonth", 1) .method(setter_method!(set_seconds(0, 1)), "setSeconds", 1) .method(setter_method!(set_year(0, 1, 2)), "setYear", 1) .method(setter_method!(set_time(0)), "setTime", 1) .method(setter_method!(set_utc_date(0)), "setUTCDate", 1) .method( setter_method!(set_utc_full_year(0, 1, 2)), "setUTCFullYear", 1, ) .method(setter_method!(set_utc_hours(0, 1, 2, 3)), "setUTCHours", 1) .method( setter_method!(set_utc_milliseconds(0)), "setUTCMilliseconds", 1, ) .method(setter_method!(set_utc_minutes(0, 1, 2)), "setUTCMinutes", 1) .method(setter_method!(set_utc_month(0, 1)), "setUTCMonth", 1) .method(setter_method!(set_utc_seconds(0, 1)), "setUTCSeconds", 1) .method(getter_method!(to_date_string), "toDateString", 0) .method(getter_method!(to_gmt_string), "toGMTString", 0) .method(getter_method!(to_iso_string), "toISOString", 0) .method(getter_method!(to_json), "toJSON", 0) // Locale strings .method(getter_method!(to_string), "toString", 0) .method(getter_method!(to_time_string), "toTimeString", 0) .method(getter_method!(to_utc_string), "toUTCString", 0) .method(getter_method!(value_of), "valueOf", 0) .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; /// Converts the `Date` to a local `DateTime`. /// /// If the `Date` is invalid (i.e. NAN), this function will return `None`. 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) -> i32 { let month = month + 1; // zero-based for calculations NaiveDate::from_ymd( match month { 12 => year + 1, _ => year, }, match month { 12 => 1, _ => month + 1, }, 1, ) .signed_duration_since(NaiveDate::from_ymd(year, month, 1)) .num_days() as i32 } #[inline] fn fix_month(year: &mut i32, month: &mut i32) { *year += *month / 12; *month = if *month < 0 { *year -= 1; 11 + (*month + 1) % 12 } else { *month % 12 } } #[inline] fn fix_day(year: &mut i32, month: &mut i32, day: &mut i32) { fix_month(year, month); loop { if *day < 0 { *month -= 1; fix_month(year, month); *day += num_days_in(*year, *month as u32); } else { let num_days = num_days_in(*year, *month as u32); if *day >= num_days { *day -= num_days_in(*year, *month as u32); *month += 1; fix_month(year, month); } else { break; } } } } // 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 mut year = year.unwrap_or_else(|| naive.year() as f64) as i32; let mut month = month.unwrap_or_else(|| naive.month0() as f64) as i32; let mut day = day.unwrap_or_else(|| naive.day() as f64) as i32 - 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_IN_MS) as i64; fix_day(&mut year, &mut month, &mut day); let duration = Duration::hours(hour) + Duration::minutes(minute) + Duration::seconds(second) + Duration::milliseconds(millisecond); NaiveDate::from_ymd_opt(year, month as u32 + 1, day as u32 + 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()) } }) }); } /// `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: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { if new_target.is_undefined() { Self::make_date_string() } else { let prototype = new_target .as_object() .and_then(|obj| { obj.get(&PROTOTYPE.into(), obj.clone().into(), context) .map(|o| o.as_object()) .transpose() }) .transpose()? .unwrap_or_else(|| context.standard_objects().object_object().prototype()); let mut obj = context.construct_object(); obj.set_prototype_instance(prototype.into()); let this = obj.into(); if args.is_empty() { 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() -> Result<Value> { Ok(Value::from(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: &Value) -> Result<Value> { let date = Date::default(); this.set_data(ObjectData::Date(date)); Ok(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: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let value = &args[0]; let tv = match this_time_value(value, context) { Ok(dt) => dt.0, _ => match value.to_primitive(context, PreferredType::Default)? { Value::String(ref str) => match chrono::DateTime::parse_from_rfc3339(&str) { Ok(dt) => Some(dt.naive_utc()), _ => None, }, tv => { let tv = tv.to_number(context)?; let secs = (tv / 1_000f64) as i64; let nsecs = ((tv % 1_000f64) * 1_000_000f64) as u32; NaiveDateTime::from_timestamp_opt(secs, nsecs) } }, }; 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: &Value, args: &[Value], context: &mut Context, ) -> Result<Value> { let 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()); } 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 }; let final_date = NaiveDate::from_ymd_opt(year, month + 1, day) .and_then(|naive_date| naive_date.and_hms_milli_opt(hour, min, sec, milli)) .and_then(|local| ignore_ambiguity(Local.from_local_datetime(&local))) .map(|local| local.naive_utc()); let date = Date(final_date); this.set_data(ObjectData::Date(date)); Ok(this.clone()) } /// `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_IN_MS) } /// `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() -> f64 { let offset_seconds = chrono::Local::now().offset().local_minus_utc() as f64; offset_seconds / 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_IN_MS) } /// `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(&mut self, day: Option<f64>) { if let Some(day) = day { self.set_components(false, None, None, Some(day), None, None, None, None) } else { self.0 = None } } /// `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(&mut self, year: Option<f64>, month: Option<f64>, day: Option<f64>) { if let Some(year) = year { self.set_components(false, Some(year), month, day, None, None, None, None) } else { self.0 = None } } /// `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( &mut self, hour: Option<f64>, minute: Option<f64>, second: Option<f64>, millisecond: Option<f64>, ) { if let Some(hour) = hour { self.set_components( false, None, None, None, Some(hour), minute, second, millisecond, ) } else { self.0 = None } } /// `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(&mut self, millisecond: Option<f64>) { if let Some(millisecond) = millisecond { self.set_components(false, None, None, None, None, None, None, Some(millisecond)) } else { self.0 = None } } /// `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( &mut self, minute: Option<f64>, second: Option<f64>, millisecond: Option<f64>, ) { if let Some(minute) = minute { self.set_components( false, None, None, None, None, Some(minute), second, millisecond, ) } else { self.0 = None } } /// `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(&mut self, month: Option<f64>, day: Option<f64>) { if let Some(month) = month { self.set_components(false, None, Some(month), day, None, None, None, None) } else { self.0 = None } } /// `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(&mut self, second: Option<f64>, millisecond: Option<f64>) { if let Some(second) = second { self.set_components( false, None, None, None, None, None, Some(second), millisecond, ) } else { self.0 = None } } /// `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(&mut self, year: Option<f64>, month: Option<f64>, day: Option<f64>) { if let Some(mut year) = year { year += if (0f64..100f64).contains(&year) { 1900f64 } else { 0f64 }; self.set_components(false, Some(year), month, day, None, None, None, None) } else { self.0 = None } } /// `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(&mut self, time: Option<f64>) { if let Some(time) = time { let secs = (time / 1_000f64) as i64; let nsecs = ((time % 1_000f64) * 1_000_000f64) as u32; self.0 = ignore_ambiguity(Local.timestamp_opt(secs, nsecs)).map(|dt| dt.naive_utc()); } else { self.0 = None } } /// `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(&mut self, day: Option<f64>) { if let Some(day) = day { self.set_components(true, None, None, Some(day), None, None, None, None) } else { self.0 = None } } /// `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(&mut self, year: Option<f64>, month: Option<f64>, day: Option<f64>) { if let Some(year) = year { self.set_components(true, Some(year), month, day, None, None, None, None) } else { self.0 = None } } /// `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( &mut self, hour: Option<f64>, minute: Option<f64>, second: Option<f64>, millisecond: Option<f64>, ) { if let Some(hour) = hour { self.set_components( true, None, None, None, Some(hour), minute, second, millisecond, ) } else { self.0 = None } } /// `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(&mut self, millisecond: Option<f64>) { if let Some(millisecond) = millisecond { self.set_components(true, None, None, None, None, None, None, Some(millisecond)) } else { self.0 = None } } /// `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( &mut self, minute: Option<f64>, second: Option<f64>, millisecond: Option<f64>, ) { if let Some(minute) = minute { self.set_components( true, None, None, None, None, Some(minute), second, millisecond, ) } else { self.0 = None } } /// `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(&mut self, month: Option<f64>, day: Option<f64>) { if let Some(month) = month { self.set_components(true, None, Some(month), day, None, None, None, None) } else { self.0 = None } } /// `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(&mut self, second: Option<f64>, millisecond: Option<f64>) { if let Some(second) = second { self.set_components( true, None, None, None, None, None, Some(second), millisecond, ) } else { self.0 = None } } /// `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 pub fn to_date_string(&self) -> String { self.to_local() .map(|date_time| date_time.format("%a %b %d %Y").to_string()) .unwrap_or_else(|| "Invalid Date".to_string()) } /// `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 pub fn to_iso_string(&self) -> String { self.to_utc() // RFC 3389 uses +0.00 for UTC, where JS expects Z, so we can't use the built-in chrono function. .map(|f| f.format("%Y-%m-%dT%H:%M:%S.%3fZ").to_string()) .unwrap_or_else(|| "Invalid Date".to_string()) } /// `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 pub fn to_json(&self) -> String { self.to_iso_string() } /// `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 pub fn to_time_string(&self) -> String { self.to_local() .map(|date_time| date_time.format("%H:%M:%S GMT%:z").to_string()) .unwrap_or_else(|| "Invalid Date".to_string()) } /// `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(_: &Value, _: &[Value], _: &mut Context) -> Result<Value> { Ok(Value::from(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(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { // This method is implementation-defined and discouraged, so we just require the same format as the string // constructor. if args.is_empty() { return Ok(Value::number(f64::NAN)); } match DateTime::parse_from_rfc3339(&args[0].to_string(context)?) { Ok(v) => Ok(Value::number(v.naive_utc().timestamp_millis() as f64)), _ => Ok(Value::number(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(_: &Value, args: &[Value], context: &mut Context) -> Result<Value> { let year = args .get(0) .map_or(Ok(f64::NAN), |value| value.to_number(context))?; let month = args .get(1) .map_or(Ok(1f64), |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(Value::number(f64::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)) .map_or(Ok(Value::number(f64::NAN)), |f| { Ok(Value::number(f.timestamp_millis() as f64)) }) } } /// 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: &Value, context: &mut Context) -> Result<Date> { if let Value::Object(ref object) = value { if let ObjectData::Date(ref date) = object.borrow().data { return Ok(*date); } } Err(context.construct_type_error("'this' is not a Date")) }