-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathdatetime.rs
More file actions
1270 lines (1136 loc) · 40.7 KB
/
datetime.rs
File metadata and controls
1270 lines (1136 loc) · 40.7 KB
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
//! This module implements `DateTime` any directly related algorithms.
use super::{
duration::normalized::{NormalizedDurationRecord, NormalizedTimeDuration},
Duration, PartialDate, PartialTime, PlainDate, PlainTime,
};
use crate::{
builtins::core::{calendar::Calendar, Instant},
iso::{IsoDate, IsoDateTime, IsoTime},
options::{
ArithmeticOverflow, DifferenceOperation, DifferenceSettings, DisplayCalendar,
ResolvedRoundingOptions, RoundingOptions, TemporalUnit, ToStringRoundingOptions,
},
parsers::{parse_date_time, IxdtfStringBuilder},
provider::NeverProvider,
temporal_assert, Sign, TemporalError, TemporalResult, TemporalUnwrap, TimeZone,
};
use alloc::string::String;
use core::{cmp::Ordering, str::FromStr};
use tinystr::TinyAsciiStr;
/// A partial PlainDateTime record
#[derive(Debug, Default, Clone)]
pub struct PartialDateTime {
/// The `PartialDate` portion of a `PartialDateTime`
pub date: PartialDate,
/// The `PartialTime` portion of a `PartialDateTime`
pub time: PartialTime,
}
/// The native Rust implementation of `Temporal.PlainDateTime`
#[non_exhaustive]
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PlainDateTime {
pub(crate) iso: IsoDateTime,
calendar: Calendar,
}
impl core::fmt::Display for PlainDateTime {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let ixdtf_str = self
.to_ixdtf_string(ToStringRoundingOptions::default(), DisplayCalendar::Auto)
.expect("ixdtf default configuration should not fail.");
f.write_str(&ixdtf_str)
}
}
impl Ord for PlainDateTime {
fn cmp(&self, other: &Self) -> Ordering {
self.iso.cmp(&other.iso)
}
}
impl PartialOrd for PlainDateTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
// ==== Private PlainDateTime API ====
impl PlainDateTime {
/// Creates a new unchecked `DateTime`.
#[inline]
#[must_use]
pub(crate) fn new_unchecked(iso: IsoDateTime, calendar: Calendar) -> Self {
Self { iso, calendar }
}
// TODO: Potentially deprecate and remove.
/// Create a new `DateTime` from an `Instant`.
#[allow(unused)]
#[inline]
pub(crate) fn from_instant(
instant: &Instant,
offset: i64,
calendar: Calendar,
) -> TemporalResult<Self> {
let iso = IsoDateTime::from_epoch_nanos(&instant.as_i128(), offset)?;
Ok(Self { iso, calendar })
}
// 5.5.14 AddDurationToOrSubtractDurationFromPlainDateTime ( operation, dateTime, temporalDurationLike, options )
fn add_or_subtract_duration(
&self,
duration: &Duration,
overflow: Option<ArithmeticOverflow>,
) -> TemporalResult<Self> {
// SKIP: 1, 2, 3, 4
// 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
// 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
// 3. Set options to ? GetOptionsObject(options).
// 4. Let calendarRec be ? CreateCalendarMethodsRecord(dateTime.[[Calendar]], « date-add »).
// 5. Let norm be NormalizeTimeDuration(sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]]).
let norm = NormalizedTimeDuration::from_time_duration(duration.time());
// TODO: validate Constrain is default with all the recent changes.
// 6. Let result be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], calendarRec, sign × duration.[[Years]], sign × duration.[[Months]], sign × duration.[[Weeks]], sign × duration.[[Days]], norm, options).
let result =
self.iso
.add_date_duration(self.calendar().clone(), duration.date(), norm, overflow)?;
// 7. Assert: IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
// 8. Assert: IsValidTime(result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]],
// result.[[Microsecond]], result.[[Nanosecond]]) is true.
temporal_assert!(
result.is_within_limits(),
"Assertion failed: the below datetime is not within valid limits:\n{:?}",
result
);
// 9. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]],
// result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]],
// result.[[Nanosecond]], dateTime.[[Calendar]]).
Ok(Self::new_unchecked(result, self.calendar.clone()))
}
/// Difference two `DateTime`s together.
pub(crate) fn diff(
&self,
op: DifferenceOperation,
other: &Self,
settings: DifferenceSettings,
) -> TemporalResult<Duration> {
// 3. If ? CalendarEquals(dateTime.[[Calendar]], other.[[Calendar]]) is false, throw a RangeError exception.
if self.calendar != other.calendar {
return Err(TemporalError::range()
.with_message("Calendar must be the same when diffing two PlainDateTimes"));
}
// 5. Let settings be ? GetDifferenceSettings(operation, resolvedOptions, datetime, « », "nanosecond", "day").
let (sign, options) = ResolvedRoundingOptions::from_diff_settings(
settings,
op,
TemporalUnit::Day,
TemporalUnit::Nanosecond,
)?;
// Step 7-8 combined.
if self.iso == other.iso {
return Ok(Duration::default());
}
// Step 10-11.
let norm_record = self.diff_dt_with_rounding(other, options)?;
let result = Duration::from_normalized(norm_record, options.largest_unit)?;
// Step 12
match sign {
Sign::Positive | Sign::Zero => Ok(result),
Sign::Negative => Ok(result.negated()),
}
}
// TODO: Figure out whether to handle resolvedOptions
// 5.5.12 DifferencePlainDateTimeWithRounding ( y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2,
// mus2, ns2, calendarRec, largestUnit, roundingIncrement, smallestUnit, roundingMode, resolvedOptions )
pub(crate) fn diff_dt_with_rounding(
&self,
other: &Self,
options: ResolvedRoundingOptions,
) -> TemporalResult<NormalizedDurationRecord> {
// 1. Assert: IsValidISODate(y1, mon1, d1) is true.
// 2. Assert: IsValidISODate(y2, mon2, d2) is true.
// 3. If CompareISODateTime(y1, mon1, d1, h1, min1, s1, ms1, mus1, ns1, y2, mon2, d2, h2, min2, s2, ms2, mus2, ns2) = 0, then
if matches!(self.iso.cmp(&other.iso), Ordering::Equal) {
// a. Let durationRecord be CreateDurationRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
// b. Return the Record { [[DurationRecord]]: durationRecord, [[Total]]: 0 }.
return Ok(NormalizedDurationRecord::default());
}
// 3. Let diff be DifferenceISODateTime(isoDateTime1, isoDateTime2, calendar, largestUnit).
let diff = self
.iso
.diff(&other.iso, &self.calendar, options.largest_unit)?;
// 4. If smallestUnit is nanosecond and roundingIncrement = 1, return diff.
if options.smallest_unit == TemporalUnit::Nanosecond && options.increment.get() == 1 {
return Ok(diff);
}
// 5. Let destEpochNs be GetUTCEpochNanoseconds(isoDateTime2).
let dest_epoch_ns = other.iso.as_nanoseconds()?;
// 6. Return ? RoundRelativeDuration(diff, destEpochNs, isoDateTime1, unset, calendar, largestUnit, roundingIncrement, smallestUnit, roundingMode).
diff.round_relative_duration(
dest_epoch_ns.0,
self,
Option::<(&TimeZone, &NeverProvider)>::None,
options,
)
}
}
// ==== Public PlainDateTime API ====
impl PlainDateTime {
/// Creates a new `DateTime`, constraining any arguments that into a valid range.
#[allow(clippy::too_many_arguments)]
pub fn new(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
millisecond: u16,
microsecond: u16,
nanosecond: u16,
calendar: Calendar,
) -> TemporalResult<Self> {
Self::new_with_overflow(
year,
month,
day,
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
calendar,
ArithmeticOverflow::Constrain,
)
}
/// Creates a new `DateTime`, rejecting any arguments that are not in a valid range.
#[allow(clippy::too_many_arguments)]
pub fn try_new(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
millisecond: u16,
microsecond: u16,
nanosecond: u16,
calendar: Calendar,
) -> TemporalResult<Self> {
Self::new_with_overflow(
year,
month,
day,
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
calendar,
ArithmeticOverflow::Reject,
)
}
/// Creates a new `DateTime` with the provided [`ArithmeticOverflow`] option.
#[inline]
#[allow(clippy::too_many_arguments)]
pub fn new_with_overflow(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
millisecond: u16,
microsecond: u16,
nanosecond: u16,
calendar: Calendar,
overflow: ArithmeticOverflow,
) -> TemporalResult<Self> {
let iso_date = IsoDate::new_with_overflow(year, month, day, overflow)?;
let iso_time = IsoTime::new(
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
overflow,
)?;
Ok(Self::new_unchecked(
IsoDateTime::new(iso_date, iso_time)?,
calendar,
))
}
/// Create a `DateTime` from a `Date` and a `Time`.
pub fn from_date_and_time(date: PlainDate, time: PlainTime) -> TemporalResult<Self> {
Ok(Self::new_unchecked(
IsoDateTime::new(date.iso, time.iso)?,
date.calendar().clone(),
))
}
/// Creates a `DateTime` from a `PartialDateTime`.
///
/// ```rust
/// use temporal_rs::{PlainDateTime, partial::{PartialDateTime, PartialTime, PartialDate}};
///
/// let date = PartialDate {
/// year: Some(2000),
/// month: Some(13),
/// day: Some(2),
/// ..Default::default()
/// };
///
/// let time = PartialTime {
/// hour: Some(4),
/// minute: Some(25),
/// ..Default::default()
/// };
///
/// let partial = PartialDateTime { date, time };
///
/// let date = PlainDateTime::from_partial(partial, None).unwrap();
///
/// assert_eq!(date.year().unwrap(), 2000);
/// assert_eq!(date.month().unwrap(), 12);
/// assert_eq!(date.day().unwrap(), 2);
/// assert_eq!(date.calendar().identifier(), "iso8601");
/// assert_eq!(date.hour(), 4);
/// assert_eq!(date.minute(), 25);
/// assert_eq!(date.second(), 0);
/// assert_eq!(date.millisecond(), 0);
///
/// ```
pub fn from_partial(
partial: PartialDateTime,
overflow: Option<ArithmeticOverflow>,
) -> TemporalResult<Self> {
let date = PlainDate::from_partial(partial.date, overflow)?;
let time = PlainTime::from_partial(partial.time, overflow)?;
Self::from_date_and_time(date, time)
}
/// Creates a new `DateTime` with the fields of a `PartialDateTime`.
///
/// ```rust
/// use temporal_rs::{Calendar, PlainDateTime, partial::{PartialDateTime, PartialTime, PartialDate}};
///
/// let initial = PlainDateTime::try_new(2000, 12, 2, 0,0,0,0,0,0, Calendar::default()).unwrap();
///
/// let date = PartialDate {
/// month: Some(5),
/// ..Default::default()
/// };
///
/// let time = PartialTime {
/// hour: Some(4),
/// second: Some(30),
/// ..Default::default()
/// };
///
/// let partial = PartialDateTime { date, time };
///
/// let date = initial.with(partial, None).unwrap();
///
/// assert_eq!(date.year().unwrap(), 2000);
/// assert_eq!(date.month().unwrap(), 5);
/// assert_eq!(date.day().unwrap(), 2);
/// assert_eq!(date.calendar().identifier(), "iso8601");
/// assert_eq!(date.hour(), 4);
/// assert_eq!(date.minute(), 0);
/// assert_eq!(date.second(), 30);
/// assert_eq!(date.millisecond(), 0);
///
/// ```
#[inline]
pub fn with(
&self,
partial_datetime: PartialDateTime,
overflow: Option<ArithmeticOverflow>,
) -> TemporalResult<Self> {
if partial_datetime.date.is_empty() && partial_datetime.time.is_empty() {
return Err(
TemporalError::r#type().with_message("A PartialDateTime must have a valid field.")
);
}
let result_date = self.calendar.date_from_partial(
&partial_datetime.date.with_fallback_datetime(self)?,
overflow.unwrap_or(ArithmeticOverflow::Constrain),
)?;
// Determine the `Time` based off the partial values.
let time = self.iso.time.with(
partial_datetime.time,
overflow.unwrap_or(ArithmeticOverflow::Constrain),
)?;
let iso_datetime = IsoDateTime::new(result_date.iso, time)?;
Ok(Self::new_unchecked(iso_datetime, self.calendar().clone()))
}
/// Creates a new `DateTime` from the current `DateTime` and the provided `Time`.
pub fn with_time(&self, time: PlainTime) -> TemporalResult<Self> {
Self::try_new(
self.iso_year(),
self.iso_month(),
self.iso_day(),
time.hour(),
time.minute(),
time.second(),
time.millisecond(),
time.microsecond(),
time.nanosecond(),
self.calendar.clone(),
)
}
/// Creates a new `DateTime` from the current `DateTime` and a provided `Calendar`.
pub fn with_calendar(&self, calendar: Calendar) -> TemporalResult<Self> {
Self::try_new(
self.iso_year(),
self.iso_month(),
self.iso_day(),
self.hour(),
self.minute(),
self.second(),
self.millisecond(),
self.microsecond(),
self.nanosecond(),
calendar,
)
}
/// Returns this `Date`'s ISO year value.
#[inline]
#[must_use]
pub const fn iso_year(&self) -> i32 {
self.iso.date.year
}
/// Returns this `Date`'s ISO month value.
#[inline]
#[must_use]
pub const fn iso_month(&self) -> u8 {
self.iso.date.month
}
/// Returns this `Date`'s ISO day value.
#[inline]
#[must_use]
pub const fn iso_day(&self) -> u8 {
self.iso.date.day
}
/// Returns the hour value
#[inline]
#[must_use]
pub fn hour(&self) -> u8 {
self.iso.time.hour
}
/// Returns the minute value
#[inline]
#[must_use]
pub fn minute(&self) -> u8 {
self.iso.time.minute
}
/// Returns the second value
#[inline]
#[must_use]
pub fn second(&self) -> u8 {
self.iso.time.second
}
/// Returns the `millisecond` value
#[inline]
#[must_use]
pub fn millisecond(&self) -> u16 {
self.iso.time.millisecond
}
/// Returns the `microsecond` value
#[inline]
#[must_use]
pub fn microsecond(&self) -> u16 {
self.iso.time.microsecond
}
/// Returns the `nanosecond` value
#[inline]
#[must_use]
pub fn nanosecond(&self) -> u16 {
self.iso.time.nanosecond
}
/// Returns the Calendar value.
#[inline]
#[must_use]
pub fn calendar(&self) -> &Calendar {
&self.calendar
}
}
// ==== Calendar-derived public API ====
impl PlainDateTime {
/// Returns the calendar year value.
pub fn year(&self) -> TemporalResult<i32> {
self.calendar.year(&self.iso.date)
}
/// Returns the calendar month value.
pub fn month(&self) -> TemporalResult<u8> {
self.calendar.month(&self.iso.date)
}
/// Returns the calendar month code value.
pub fn month_code(&self) -> TemporalResult<TinyAsciiStr<4>> {
self.calendar.month_code(&self.iso.date)
}
/// Returns the calendar day value.
pub fn day(&self) -> TemporalResult<u8> {
self.calendar.day(&self.iso.date)
}
/// Returns the calendar day of week value.
pub fn day_of_week(&self) -> TemporalResult<u16> {
self.calendar.day_of_week(&self.iso.date)
}
/// Returns the calendar day of year value.
pub fn day_of_year(&self) -> TemporalResult<u16> {
self.calendar.day_of_year(&self.iso.date)
}
/// Returns the calendar week of year value.
pub fn week_of_year(&self) -> TemporalResult<Option<u16>> {
self.calendar.week_of_year(&self.iso.date)
}
/// Returns the calendar year of week value.
pub fn year_of_week(&self) -> TemporalResult<Option<i32>> {
self.calendar.year_of_week(&self.iso.date)
}
/// Returns the calendar days in week value.
pub fn days_in_week(&self) -> TemporalResult<u16> {
self.calendar.days_in_week(&self.iso.date)
}
/// Returns the calendar days in month value.
pub fn days_in_month(&self) -> TemporalResult<u16> {
self.calendar.days_in_month(&self.iso.date)
}
/// Returns the calendar days in year value.
pub fn days_in_year(&self) -> TemporalResult<u16> {
self.calendar.days_in_year(&self.iso.date)
}
/// Returns the calendar months in year value.
pub fn months_in_year(&self) -> TemporalResult<u16> {
self.calendar.months_in_year(&self.iso.date)
}
/// Returns returns whether the date in a leap year for the given calendar.
pub fn in_leap_year(&self) -> TemporalResult<bool> {
self.calendar.in_leap_year(&self.iso.date)
}
pub fn era(&self) -> TemporalResult<Option<TinyAsciiStr<16>>> {
self.calendar.era(&self.iso.date)
}
pub fn era_year(&self) -> TemporalResult<Option<i32>> {
self.calendar.era_year(&self.iso.date)
}
}
impl PlainDateTime {
#[inline]
/// Adds a `Duration` to the current `DateTime`.
pub fn add(
&self,
duration: &Duration,
overflow: Option<ArithmeticOverflow>,
) -> TemporalResult<Self> {
self.add_or_subtract_duration(duration, overflow)
}
#[inline]
/// Subtracts a `Duration` to the current `DateTime`.
pub fn subtract(
&self,
duration: &Duration,
overflow: Option<ArithmeticOverflow>,
) -> TemporalResult<Self> {
self.add_or_subtract_duration(&duration.negated(), overflow)
}
#[inline]
/// Returns a `Duration` representing the period of time from this `DateTime` until the other `DateTime`.
pub fn until(&self, other: &Self, settings: DifferenceSettings) -> TemporalResult<Duration> {
self.diff(DifferenceOperation::Until, other, settings)
}
#[inline]
/// Returns a `Duration` representing the period of time from this `DateTime` since the other `DateTime`.
pub fn since(&self, other: &Self, settings: DifferenceSettings) -> TemporalResult<Duration> {
self.diff(DifferenceOperation::Since, other, settings)
}
/// Rounds the current datetime based on provided options.
pub fn round(&self, options: RoundingOptions) -> TemporalResult<Self> {
let resolved = ResolvedRoundingOptions::from_dt_options(options)?;
if resolved.is_noop() {
return Ok(self.clone());
}
let result = self.iso.round(resolved)?;
Ok(Self::new_unchecked(result, self.calendar.clone()))
}
pub fn to_ixdtf_string(
&self,
options: ToStringRoundingOptions,
display_calendar: DisplayCalendar,
) -> TemporalResult<String> {
let resolved_options = options.resolve()?;
let result = self
.iso
.round(ResolvedRoundingOptions::from_to_string_options(
&resolved_options,
))?;
if !result.is_within_limits() {
return Err(TemporalError::range().with_message("DateTime is not within valid limits."));
}
let ixdtf_string = IxdtfStringBuilder::default()
.with_date(result.date)
.with_time(result.time, resolved_options.precision)
.with_calendar(self.calendar.identifier(), display_calendar)
.build();
Ok(ixdtf_string)
}
}
// ==== Trait impls ====
impl From<PlainDate> for PlainDateTime {
fn from(value: PlainDate) -> Self {
PlainDateTime::new_unchecked(
IsoDateTime::new_unchecked(value.iso, IsoTime::default()),
value.calendar().clone(),
)
}
}
impl FromStr for PlainDateTime {
type Err = TemporalError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parse_record = parse_date_time(s)?;
let calendar = parse_record
.calendar
.map(Calendar::from_utf8)
.transpose()?
.unwrap_or_default();
let time = parse_record
.time
.map(|time| {
IsoTime::from_components(time.hour, time.minute, time.second, time.nanosecond)
})
.transpose()?
.unwrap_or_default();
let parsed_date = parse_record.date.temporal_unwrap()?;
let date = IsoDate::new_with_overflow(
parsed_date.year,
parsed_date.month,
parsed_date.day,
ArithmeticOverflow::Reject,
)?;
Ok(Self::new_unchecked(IsoDateTime::new(date, time)?, calendar))
}
}
#[cfg(test)]
mod tests {
use tinystr::{tinystr, TinyAsciiStr};
use crate::{
builtins::core::{
calendar::Calendar, duration::DateDuration, Duration, PartialDate, PartialDateTime,
PartialTime, PlainDateTime,
},
iso::{IsoDate, IsoDateTime, IsoTime},
options::{
DifferenceSettings, DisplayCalendar, RoundingIncrement, RoundingOptions,
TemporalRoundingMode, TemporalUnit, ToStringRoundingOptions,
},
parsers::Precision,
primitive::FiniteF64,
TemporalResult,
};
fn assert_datetime(
dt: PlainDateTime,
fields: (i32, u8, TinyAsciiStr<4>, u8, u8, u8, u8, u16, u16, u16),
) {
assert_eq!(dt.year().unwrap(), fields.0);
assert_eq!(dt.month().unwrap(), fields.1);
assert_eq!(dt.month_code().unwrap(), fields.2);
assert_eq!(dt.day().unwrap(), fields.3);
assert_eq!(dt.hour(), fields.4);
assert_eq!(dt.minute(), fields.5);
assert_eq!(dt.second(), fields.6);
assert_eq!(dt.millisecond(), fields.7);
assert_eq!(dt.microsecond(), fields.8);
assert_eq!(dt.nanosecond(), fields.9);
}
fn pdt_from_date(year: i32, month: u8, day: u8) -> TemporalResult<PlainDateTime> {
PlainDateTime::try_new(year, month, day, 0, 0, 0, 0, 0, 0, Calendar::default())
}
#[test]
#[allow(clippy::float_cmp)]
fn plain_date_time_limits() {
// This test is primarily to assert that the `expect` in the epoch methods is
// valid, i.e., a valid instant is within the range of an f64.
let negative_limit = pdt_from_date(-271_821, 4, 19);
assert!(negative_limit.is_err());
let positive_limit = pdt_from_date(275_760, 9, 14);
assert!(positive_limit.is_err());
let within_negative_limit = pdt_from_date(-271_821, 4, 20);
assert_eq!(
within_negative_limit,
Ok(PlainDateTime {
iso: IsoDateTime {
date: IsoDate {
year: -271_821,
month: 4,
day: 20,
},
time: IsoTime::default(),
},
calendar: Calendar::default(),
})
);
let within_positive_limit = pdt_from_date(275_760, 9, 13);
assert_eq!(
within_positive_limit,
Ok(PlainDateTime {
iso: IsoDateTime {
date: IsoDate {
year: 275_760,
month: 9,
day: 13,
},
time: IsoTime::default(),
},
calendar: Calendar::default(),
})
);
}
#[test]
fn basic_with_test() {
let pdt =
PlainDateTime::try_new(1976, 11, 18, 15, 23, 30, 123, 456, 789, Calendar::default())
.unwrap();
// Test year
let partial = PartialDateTime {
date: PartialDate {
year: Some(2019),
..Default::default()
},
time: PartialTime::default(),
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(2019, 11, tinystr!(4, "M11"), 18, 15, 23, 30, 123, 456, 789),
);
// Test month
let partial = PartialDateTime {
date: PartialDate {
month: Some(5),
..Default::default()
},
time: PartialTime::default(),
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 5, tinystr!(4, "M05"), 18, 15, 23, 30, 123, 456, 789),
);
// Test monthCode
let partial = PartialDateTime {
date: PartialDate {
month_code: Some(tinystr!(4, "M05")),
..Default::default()
},
time: PartialTime::default(),
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 5, tinystr!(4, "M05"), 18, 15, 23, 30, 123, 456, 789),
);
// Test day
let partial = PartialDateTime {
date: PartialDate {
day: Some(5),
..Default::default()
},
time: PartialTime::default(),
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 5, 15, 23, 30, 123, 456, 789),
);
// Test hour
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
hour: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 5, 23, 30, 123, 456, 789),
);
// Test minute
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
minute: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 15, 5, 30, 123, 456, 789),
);
// Test second
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
second: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 15, 23, 5, 123, 456, 789),
);
// Test second
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
millisecond: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 15, 23, 30, 5, 456, 789),
);
// Test second
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
microsecond: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 15, 23, 30, 123, 5, 789),
);
// Test second
let partial = PartialDateTime {
date: PartialDate::default(),
time: PartialTime {
nanosecond: Some(5),
..Default::default()
},
};
let result = pdt.with(partial, None).unwrap();
assert_datetime(
result,
(1976, 11, tinystr!(4, "M11"), 18, 15, 23, 30, 123, 456, 5),
);
}
#[test]
fn datetime_with_empty_partial() {
let pdt =
PlainDateTime::try_new(2020, 1, 31, 12, 34, 56, 987, 654, 321, Calendar::default())
.unwrap();
let err = pdt.with(PartialDateTime::default(), None);
assert!(err.is_err());
}
// options-undefined.js
#[test]
fn datetime_add_test() {
let pdt =
PlainDateTime::try_new(2020, 1, 31, 12, 34, 56, 987, 654, 321, Calendar::default())
.unwrap();
let result = pdt
.add(
&Duration::from(
DateDuration::new(
FiniteF64::default(),
FiniteF64(1.0),
FiniteF64::default(),
FiniteF64::default(),
)
.unwrap(),
),
None,
)
.unwrap();
assert_eq!(result.month(), Ok(2));
assert_eq!(result.day(), Ok(29));
}
// options-undefined.js
#[test]
fn datetime_subtract_test() {
let pdt =
PlainDateTime::try_new(2000, 3, 31, 12, 34, 56, 987, 654, 321, Calendar::default())
.unwrap();
let result = pdt
.subtract(
&Duration::from(
DateDuration::new(
FiniteF64::default(),
FiniteF64(1.0),
FiniteF64::default(),
FiniteF64::default(),
)
.unwrap(),
),
None,
)
.unwrap();
assert_eq!(result.month(), Ok(2));
assert_eq!(result.day(), Ok(29));
}
// subtract/hour-overflow.js
#[test]
fn datetime_subtract_hour_overflows() {
let dt =
PlainDateTime::try_new(2019, 10, 29, 10, 46, 38, 271, 986, 102, Calendar::default())
.unwrap();
let result = dt.subtract(&Duration::hour(FiniteF64(12.0)), None).unwrap();
assert_datetime(
result,
(2019, 10, tinystr!(4, "M10"), 28, 22, 46, 38, 271, 986, 102),
);
let result = dt.add(&Duration::hour(FiniteF64(-12.0)), None).unwrap();
assert_datetime(
result,
(2019, 10, tinystr!(4, "M10"), 28, 22, 46, 38, 271, 986, 102),
);
}
fn create_diff_setting(