Skip to main content

DateTime

Struct DateTime 

Source
pub struct DateTime { /* private fields */ }
Expand description

A precise instant in time together with a TimeZone.

A DateTime is always absolute: it is represented as nanoseconds since the Unix epoch (with nanosecond precision) plus the time zone used to display it. Comparisons and subtraction operate on the instant only.

The supported UTC calendar range is -9999-01-01 through 9999-12-31. (A value near the boundary can display a year one outside this range when a large UTC offset is applied.)

§Examples

use time::DateTime;

let dt: DateTime = "2024-02-29T12:00:00Z".parse().unwrap();
assert_eq!(dt.year(), 2024);
assert_eq!(dt.month(), 2);
assert_eq!(dt.day(), 29);

Implementations§

Source§

impl DateTime

Source

pub const UNIX_EPOCH: DateTime

The Unix epoch, 1970-01-01T00:00:00Z.

Source

pub fn from_unix(seconds: i64) -> Result<DateTime, Error>

Creates a DateTime from whole seconds since the Unix epoch, in UTC.

§Errors

Returns an error if the instant is outside the supported range.

Source

pub fn from_unix_nanos(nanoseconds: i128) -> Result<DateTime, Error>

Creates a DateTime from nanoseconds since the Unix epoch, in UTC.

§Errors

Returns an error if the instant is outside the supported range.

Source

pub fn from_parts( year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, nanosecond: u32, zone: TimeZone, ) -> Result<DateTime, Error>

Creates a DateTime from civil fields in the given time zone.

A civil time that is skipped by a DST transition is shifted forward; a civil time that occurs twice selects the earlier instant. Use DateTime::from_parts_with to choose another strategy, or TimeZone::ambiguity to inspect the mapping. A leap second (second == 60) is accepted and represented as :59 of the same minute; the library never produces :60 on output.

§Errors

Returns an error if any field is out of range, or if the resulting instant is outside the supported range.

Source

pub fn from_parts_with( year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, nanosecond: u32, zone: TimeZone, disambiguation: Disambiguation, ) -> Result<DateTime, Error>

Creates a DateTime from civil fields, resolving any ambiguity or gap with the given Disambiguation strategy.

§Errors

Returns an error if any field is out of range, if the resulting instant is outside the supported range, or if disambiguation is Disambiguation::Reject and the civil time is ambiguous or does not exist (see ErrorKind::Ambiguous).

Source

pub fn now_in(zone: TimeZone) -> DateTime

Returns the current time in the given time zone.

Source

pub fn now() -> DateTime

Returns the current time in the system’s local time zone.

With the timezone-system feature the system zone is used, falling back to UTC if it cannot be determined. Without that feature this is UTC.

Source

pub fn parse_with_timezone( input: &str, zone: TimeZone, ) -> Result<DateTime, Error>

Parses a string, interpreting zone-less input in zone.

This is str::parse with an explicit default zone. An offset or zone annotation in the input always takes precedence.

§Errors

Returns an error if the input cannot be parsed or is out of range.

Source

pub fn parse_bytes(input: &[u8]) -> Result<DateTime, Error>

Parses a byte slice, interpreting zone-less input as UTC.

This accepts the same grammar as str::parse and never allocates; non-UTF-8 input is rejected.

§Errors

Returns an error if the input cannot be parsed or is out of range.

Source

pub fn parse_bytes_with_timezone( input: &[u8], zone: TimeZone, ) -> Result<DateTime, Error>

Parses a byte slice, interpreting zone-less input in zone.

§Errors

Returns an error if the input cannot be parsed or is out of range.

Source

pub fn parse_bytes_with_format( input: &[u8], format: Format, ) -> Result<DateTime, Error>

Parses a byte slice using a specific Format.

This accepts the same grammar as DateTime::parse_with_format and never allocates; non-UTF-8 input is rejected.

§Errors

Returns an error if the input cannot be parsed or is out of range.

Source

pub fn parse_with_format(input: &str, format: Format) -> Result<DateTime, Error>

Parses a string using a specific Format.

TimeOnly input is interpreted on the Unix epoch date (1970-01-01).

§Errors

Returns an error if the input cannot be parsed or is out of range.

Source

pub fn format(&self, format: Format) -> Formatted<'_>

Returns a best-effort Display adapter for format.

This never fails. Formats with a restricted domain can emit a non-conforming string for out-of-domain values; see Format and use DateTime::try_format for strict output.

Source

pub fn try_format(&self, format: Format) -> Result<Formatted<'_>, Error>

Returns a Display adapter, checking up front that the value is representable in format.

Unlike DateTime::format, this rejects values that the format cannot express conformantly: a year outside 0000..=9999 for every format except Format::TimeOnly, and a UTC offset with a seconds component for the RFC 3339, RFC 9557, ISO 8601 and RFC 2822 formats.

§Errors

Returns ErrorKind::OutOfRange if the value cannot be represented in the requested format.

Source

pub fn format_to( &self, buffer: &mut [u8], format: Format, ) -> Result<usize, Error>

Writes this value in format into buffer without allocating, and returns the number of bytes written.

This is the allocation-free companion of DateTime::format: it applies the same strict representability checks as DateTime::try_format, so it works in no_std environments without alloc.

§Errors

Returns ErrorKind::OutOfRange if the value cannot be represented in format, or ErrorKind::BufferTooSmall if buffer is too small.

Source

pub const fn unix(&self) -> i64

Returns the number of whole seconds since the Unix epoch.

Source

pub const fn unix_nanos(&self) -> i128

Returns the number of nanoseconds since the Unix epoch.

Source

pub const fn offset(&self) -> i32

Returns the UTC offset in seconds east of Greenwich.

Source

pub const fn timezone(&self) -> TimeZone

Returns the time zone associated with this value.

Source

pub const fn timezone_name(&self) -> Option<&'static str>

Returns the canonical name of the time zone, if it has one.

Source

pub fn is_dst(&self) -> bool

Returns true if daylight saving time is in effect.

Source

pub fn in_timezone(&self, zone: TimeZone) -> DateTime

Returns the local time at this instant in zone.

Source

pub fn year(&self) -> i32

Returns the calendar year.

Source

pub fn month(&self) -> u8

Returns the month (1..=12).

Source

pub fn day(&self) -> u8

Returns the day of the month (1..=31).

Source

pub fn hour(&self) -> u8

Returns the hour (0..=23).

Source

pub fn minute(&self) -> u8

Returns the minute (0..=59).

Source

pub fn second(&self) -> u8

Returns the second (0..=59).

Source

pub fn nanosecond(&self) -> u32

Returns the nanosecond (0..1_000_000_000).

Source

pub fn millisecond(&self) -> u32

Returns the millisecond (0..1000).

Source

pub fn microsecond(&self) -> u32

Returns the microsecond (0..1_000_000).

Source

pub fn weekday(&self) -> Weekday

Returns the day of the week.

Source

pub fn ordinal(&self) -> u16

Returns the day of the year (1..=366).

Source

pub fn iso_week(&self) -> (i32, u8)

Returns the ISO 8601 week-based year and week number.

Source

pub fn checked_add(&self, duration: Duration) -> Result<DateTime, Error>

Adds a Duration to this instant.

§Errors

Returns an error if the result is out of range.

Source

pub fn checked_sub(&self, duration: Duration) -> Result<DateTime, Error>

Subtracts a Duration from this instant.

§Errors

Returns an error if the result is out of range.

Source

pub fn saturating_add(&self, duration: Duration) -> DateTime

Adds a duration, saturating at the supported range boundaries.

Source

pub fn saturating_sub(&self, duration: Duration) -> DateTime

Subtracts a duration, saturating at the supported range boundaries.

Source

pub fn duration_since(&self, earlier: DateTime) -> Result<Duration, Error>

Returns the duration from earlier to self.

When both values were produced by DateTime::now or DateTime::now_in, the measurement uses the monotonic clock and is therefore robust against wall-clock adjustments (for example NTP steps). Otherwise the wall clock is used.

§Errors

Returns an error if earlier is later than self.

Source

pub fn duration_until(&self, later: DateTime) -> Result<Duration, Error>

Returns the duration from self to later.

This is the inverse of DateTime::duration_since and follows the same monotonic-clock rules.

§Errors

Returns an error if later is earlier than self.

Source

pub fn signed_duration_since(&self, other: DateTime) -> (i64, u32)

Returns the signed difference self - other as (seconds, subsecond_nanoseconds), where the sign is carried by seconds and the nanosecond component is always in 0..=999_999_999.

The monotonic clock is used when both values carry a reading (see DateTime::duration_since).

Source

pub fn elapsed(&self) -> Result<Duration, Error>

Returns the time elapsed since this value was created.

§Errors

Returns an error if the system clock reports a value before this one (only possible without a monotonic reading).

Source

pub const fn has_monotonic(&self) -> bool

Returns true if this value carries a monotonic clock reading, which DateTime::now and DateTime::now_in add so that elapsed-time measurement is robust against wall-clock adjustments.

Source

pub fn abbreviation(&self) -> Option<&'static str>

Returns the time zone abbreviation in effect, such as EST, when the zone has one (UTC reports UTC; fixed offsets have none).

Source

pub fn zone_bounds(&self) -> (Option<DateTime>, Option<DateTime>)

Returns the bounds of the constant-offset period that contains this instant, each as an optional DateTime where None means unbounded in that direction.

Bounds are reported for embedded-database zones and only span explicit transitions. The database materializes future daylight-saving transitions up to a rolling horizon (the IANA release year plus 50), so dates beyond that horizon have an unbounded end even while a DST rule applies; fixed offsets and UTC are always unbounded.

Source

pub fn add_days(&self, days: i64) -> Result<DateTime, Error>

Adds whole calendar days, preserving the local time of day across DST transitions.

§Errors

Returns an error if the result is out of range.

Source

pub fn add_months(&self, months: i32) -> Result<DateTime, Error>

Adds whole calendar months, clamping the day to the end of the target month.

§Errors

Returns an error if the result is out of range.

Source

pub fn add_years(&self, years: i32) -> Result<DateTime, Error>

Adds whole calendar years, clamping February 29 to February 28 in non-leap years.

§Errors

Returns an error if the result is out of range.

Trait Implementations§

Source§

impl Add<Duration> for DateTime

Source§

fn add(self, rhs: Duration) -> DateTime

Adds a duration, panicking if the result is out of range.

Source§

type Output = DateTime

The resulting type after applying the + operator.
Source§

impl AddAssign<Duration> for DateTime

Source§

fn add_assign(&mut self, rhs: Duration)

Performs the += operation. Read more
Source§

impl Clone for DateTime

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Copy for DateTime

Source§

impl Debug for DateTime

Source§

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

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

impl Default for DateTime

Source§

fn default() -> DateTime

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

impl<'de> Deserialize<'de> for DateTime

Source§

fn deserialize<D>(deserializer: D) -> Result<DateTime, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for DateTime

Source§

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

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

impl Eq for DateTime

Source§

impl From<DateTime> for SystemTime

Available on crate feature std only.
Source§

fn from(dt: DateTime) -> SystemTime

Converts this value into a SystemTime.

The supported calendar range fits within SystemTime on common platforms; on platforms with a narrower SystemTime this saturates to the Unix epoch rather than panicking.

Source§

impl FromStr for DateTime

Source§

type Err = Error

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

fn from_str(s: &str) -> Result<DateTime, Error>

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

impl Hash for DateTime

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DateTime

Source§

fn cmp(&self, other: &DateTime) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for DateTime

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialOrd for DateTime

Source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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 (const: unstable) · 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 Serialize for DateTime

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Sub<Duration> for DateTime

Source§

fn sub(self, rhs: Duration) -> DateTime

Subtracts a duration, panicking if the result is out of range.

Source§

type Output = DateTime

The resulting type after applying the - operator.
Source§

impl SubAssign<Duration> for DateTime

Source§

fn sub_assign(&mut self, rhs: Duration)

Performs the -= operation. Read more
Source§

impl TryFrom<SystemTime> for DateTime

Available on crate feature std only.
Source§

fn try_from(value: SystemTime) -> Result<DateTime, Error>

Converts a SystemTime into a DateTime.

§Errors

Returns an error if the instant is outside the supported range.

Source§

type Error = Error

The type returned in the event of a conversion error.

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.