#[non_exhaustive]pub struct Duration { /* private fields */ }Expand description
The native Rust implementation of Temporal.Duration.
Represents a span of time such as “2 hours and 30 minutes” or “3 years, 2 months”.
Unlike Instant which represents a specific moment in time, Duration represents
the amount of time between two moments.
A Duration consists of two categories of components:
- Date components: years, months, weeks, and days
- Time components: hours, minutes, seconds, and subsecond units (nanosecond precision)
Note that date arithmetic can be complex. For example, adding “1 month” to January 31st could result in February 28th (non-leap year), February 29th (leap year), or March 3rd (if you overflow February), depending on the calendar system and overflow handling.
§Examples
§Creating durations
use temporal_rs::Duration;
// Create a duration with specific components
let vacation_duration = Duration::new(
0, 0, 2, 3, // 2 weeks and 3 days
0, 0, 0, // no time components
0, 0, 0 // no subsecond components
).unwrap();
assert_eq!(vacation_duration.weeks(), 2);
assert_eq!(vacation_duration.days(), 3);§Parsing ISO 8601 duration strings
use temporal_rs::Duration;
use core::str::FromStr;
// Complex duration with multiple components
let complex = Duration::from_str("P1Y2M3DT4H5M6.789S").unwrap();
assert_eq!(complex.years(), 1);
assert_eq!(complex.months(), 2);
assert_eq!(complex.days(), 3);
assert_eq!(complex.hours(), 4);
assert_eq!(complex.minutes(), 5);
assert_eq!(complex.seconds(), 6);
// Time-only duration
let movie_length = Duration::from_str("PT2H30M").unwrap();
assert_eq!(movie_length.hours(), 2);
assert_eq!(movie_length.minutes(), 30);
// Negative durations
let negative = Duration::from_str("-P1D").unwrap();
assert_eq!(negative.days(), -1);§Duration arithmetic
use temporal_rs::Duration;
use core::str::FromStr;
let commute_time = Duration::from_str("PT45M").unwrap();
let lunch_break = Duration::from_str("PT1H").unwrap();
// Add durations together
let total_time = commute_time.add(&lunch_break).unwrap();
assert_eq!(total_time.hours(), 1); // Results in 1 hour 45 minutes
assert_eq!(total_time.minutes(), 45);
// Subtract duration components
let shortened = lunch_break.subtract(&Duration::from_str("PT15M").unwrap()).unwrap();
assert_eq!(shortened.minutes(), 45);§Date arithmetic with durations
use temporal_rs::{PlainDate, Duration, options::Overflow};
use core::str::FromStr;
// January 31st in different years
let jan_31_2023 = PlainDate::try_new_iso(2023, 1, 31).unwrap();
let jan_31_2024 = PlainDate::try_new_iso(2024, 1, 31).unwrap(); // leap year
let one_month = Duration::from_str("P1M").unwrap();
// Adding 1 month to Jan 31st gives different results:
let feb_2023 = jan_31_2023.add(&one_month, Some(Overflow::Constrain)).unwrap();
let feb_2024 = jan_31_2024.add(&one_month, Some(Overflow::Constrain)).unwrap();
// 2023: Jan 31 + 1 month = Feb 28 (no Feb 31st exists)
assert_eq!(feb_2023.day(), 28);
// 2024: Jan 31 + 1 month = Feb 29 (leap year)
assert_eq!(feb_2024.day(), 29);§Working with partial durations
use temporal_rs::{Duration, partial::PartialDuration};
let partial = PartialDuration {
hours: Some(3),
minutes: Some(45),
..Default::default()
};
let duration = Duration::from_partial_duration(partial).unwrap();
assert_eq!(duration.hours(), 3);
assert_eq!(duration.minutes(), 45);
assert_eq!(duration.days(), 0); // other fields default to 0§Duration properties
use temporal_rs::Duration;
use core::str::FromStr;
let duration = Duration::from_str("P1Y2M3D").unwrap();
// Check if duration is zero
assert!(!duration.is_zero());
// Get the sign of the duration
let sign = duration.sign();
// Note: This particular duration has mixed signs which affects the overall sign
// Get absolute value
let abs_duration = duration.abs();
assert_eq!(abs_duration.years(), 1);
assert_eq!(abs_duration.months(), 2);
assert_eq!(abs_duration.days(), 3);
// Negate duration
let negated = duration.negated();
assert_eq!(negated.years(), -1);
assert_eq!(negated.months(), -2);
assert_eq!(negated.days(), -3);§Reference
For more information, see the MDN documentation.
Implementations§
Source§impl Duration
impl Duration
Sourcepub fn round(
&self,
options: RoundingOptions,
relative_to: Option<RelativeTo>,
) -> TemporalResult<Self>
pub fn round( &self, options: RoundingOptions, relative_to: Option<RelativeTo>, ) -> TemporalResult<Self>
Rounds the current Duration according to the provided RoundingOptions and an optional
RelativeTo
Enable with the compiled_data feature flag.
Sourcepub fn compare(
&self,
two: &Duration,
relative_to: Option<RelativeTo>,
) -> TemporalResult<Ordering>
pub fn compare( &self, two: &Duration, relative_to: Option<RelativeTo>, ) -> TemporalResult<Ordering>
Returns the ordering between two Duration, takes an optional
RelativeTo
Enable with the compiled_data feature flag.
pub fn total( &self, unit: Unit, relative_to: Option<RelativeTo>, ) -> TemporalResult<FiniteF64>
Source§impl Duration
impl Duration
Sourcepub fn new(
years: i64,
months: i64,
weeks: i64,
days: i64,
hours: i64,
minutes: i64,
seconds: i64,
milliseconds: i64,
microseconds: i128,
nanoseconds: i128,
) -> TemporalResult<Self>
pub fn new( years: i64, months: i64, weeks: i64, days: i64, hours: i64, minutes: i64, seconds: i64, milliseconds: i64, microseconds: i128, nanoseconds: i128, ) -> TemporalResult<Self>
Creates a new validated Duration.
Sourcepub fn from_partial_duration(partial: PartialDuration) -> TemporalResult<Self>
pub fn from_partial_duration(partial: PartialDuration) -> TemporalResult<Self>
Creates a Duration from a provided PartialDuration.
§Examples
use temporal_rs::{partial::PartialDuration, Duration};
let duration = Duration::from_partial_duration(PartialDuration {
seconds: Some(4),
..Default::default()
}).unwrap();
assert_eq!(duration.seconds(), 4);
assert_eq!(duration.to_string(), "PT4S");pub fn from_utf8(s: &[u8]) -> TemporalResult<Self>
Sourcepub fn is_time_within_range(&self) -> bool
pub fn is_time_within_range(&self) -> bool
Return if the Durations values are within their valid ranges.
pub fn compare_with_provider( &self, other: &Duration, relative_to: Option<RelativeTo>, provider: &(impl TimeZoneProvider + ?Sized), ) -> TemporalResult<Ordering>
Source§impl Duration
impl Duration
Sourcepub fn date(&self) -> DateDuration
pub fn date(&self) -> DateDuration
Returns a reference to the inner DateDuration
Sourcepub const fn milliseconds(&self) -> i64
pub const fn milliseconds(&self) -> i64
Returns the hours field of duration.
Sourcepub const fn microseconds(&self) -> i128
pub const fn microseconds(&self) -> i128
Returns the microseconds field of duration.
Sourcepub const fn nanoseconds(&self) -> i128
pub const fn nanoseconds(&self) -> i128
Returns the nanoseconds field of duration.
Source§impl Duration
impl Duration
Sourcepub fn is_zero(&self) -> bool
pub fn is_zero(&self) -> bool
Returns whether the current Duration is zero.
Equivalant to Temporal.Duration.blank().
Sourcepub fn add(&self, other: &Self) -> TemporalResult<Self>
pub fn add(&self, other: &Self) -> TemporalResult<Self>
Returns the result of adding a Duration to the current Duration
Sourcepub fn subtract(&self, other: &Self) -> TemporalResult<Self>
pub fn subtract(&self, other: &Self) -> TemporalResult<Self>
Returns the result of subtracting a Duration from the current Duration
Sourcepub fn round_with_provider(
&self,
options: RoundingOptions,
relative_to: Option<RelativeTo>,
provider: &(impl TimeZoneProvider + ?Sized),
) -> TemporalResult<Self>
pub fn round_with_provider( &self, options: RoundingOptions, relative_to: Option<RelativeTo>, provider: &(impl TimeZoneProvider + ?Sized), ) -> TemporalResult<Self>
17.3.20 Temporal.Duration.prototype.round ( roundTo )
Spec: https://tc39.es/proposal-temporal/#sec-temporal.duration.prototype.round
Sourcepub fn total_with_provider(
&self,
unit: Unit,
relative_to: Option<RelativeTo>,
provider: &(impl TimeZoneProvider + ?Sized),
) -> TemporalResult<FiniteF64>
pub fn total_with_provider( &self, unit: Unit, relative_to: Option<RelativeTo>, provider: &(impl TimeZoneProvider + ?Sized), ) -> TemporalResult<FiniteF64>
Returns the total of the Duration
Sourcepub fn as_temporal_string(
&self,
options: ToStringRoundingOptions,
) -> TemporalResult<String>
pub fn as_temporal_string( &self, options: ToStringRoundingOptions, ) -> TemporalResult<String>
Returns the Duration as a formatted string