Duration

Struct Duration 

Source
#[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

Source

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.

Source

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.

Source

pub fn total( &self, unit: Unit, relative_to: Option<RelativeTo>, ) -> TemporalResult<FiniteF64>

Source§

impl Duration

Source

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.

Source

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");
Source

pub fn from_utf8(s: &[u8]) -> TemporalResult<Self>

Source

pub fn is_time_within_range(&self) -> bool

Return if the Durations values are within their valid ranges.

Source

pub fn compare_with_provider( &self, other: &Duration, relative_to: Option<RelativeTo>, provider: &(impl TimeZoneProvider + ?Sized), ) -> TemporalResult<Ordering>

Source§

impl Duration

Source

pub fn date(&self) -> DateDuration

Returns a reference to the inner DateDuration

Source

pub const fn years(&self) -> i64

Returns the years field of duration.

Source

pub const fn months(&self) -> i64

Returns the months field of duration.

Source

pub const fn weeks(&self) -> i64

Returns the weeks field of duration.

Source

pub const fn days(&self) -> i64

Returns the days field of duration.

Source

pub const fn hours(&self) -> i64

Returns the hours field of duration.

Source

pub const fn minutes(&self) -> i64

Returns the hours field of duration.

Source

pub const fn seconds(&self) -> i64

Returns the seconds field of duration.

Source

pub const fn milliseconds(&self) -> i64

Returns the hours field of duration.

Source

pub const fn microseconds(&self) -> i128

Returns the microseconds field of duration.

Source

pub const fn nanoseconds(&self) -> i128

Returns the nanoseconds field of duration.

Source§

impl Duration

Source

pub fn sign(&self) -> Sign

Determines the sign for the current self.

Source

pub fn is_zero(&self) -> bool

Returns whether the current Duration is zero.

Equivalant to Temporal.Duration.blank().

Source

pub fn negated(&self) -> Self

Returns a negated Duration

Source

pub fn abs(&self) -> Self

Returns the absolute value of Duration.

Source

pub fn add(&self, other: &Self) -> TemporalResult<Self>

Returns the result of adding a Duration to the current Duration

Source

pub fn subtract(&self, other: &Self) -> TemporalResult<Self>

Returns the result of subtracting a Duration from the current Duration

Source

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

Source

pub fn total_with_provider( &self, unit: Unit, relative_to: Option<RelativeTo>, provider: &(impl TimeZoneProvider + ?Sized), ) -> TemporalResult<FiniteF64>

Returns the total of the Duration

Source

pub fn as_temporal_string( &self, options: ToStringRoundingOptions, ) -> TemporalResult<String>

Returns the Duration as a formatted string

Trait Implementations§

Source§

impl Clone for Duration

Source§

fn clone(&self) -> Duration

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Duration

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Duration

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Duration

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<&Duration> for DateDuration

Source§

fn from(duration: &Duration) -> Self

Converts a Duration into a DateDuration.

This conversion is lossy, as Duration can represent time durations that are not strictly date durations.

Source§

impl From<DateDuration> for Duration

Source§

fn from(value: DateDuration) -> Self

Converts to this type from the input type.
Source§

impl From<Duration> for DateDuration

Source§

fn from(duration: Duration) -> Self

Converts a Duration into a DateDuration.

This conversion is lossy, as Duration can represent time durations that are not strictly date durations.

Source§

impl FromStr for Duration

Source§

type Err = TemporalError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl PartialEq for Duration

Source§

fn eq(&self, other: &Duration) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Duration

Source§

fn partial_cmp(&self, other: &Duration) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl TryFrom<PartialDuration> for Duration

Source§

type Error = TemporalError

The type returned in the event of a conversion error.
Source§

fn try_from(partial: PartialDuration) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for Duration

Source§

impl StructuralPartialEq for Duration

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> ErasedDestructor for T
where T: 'static,