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
impl DateTime
Sourcepub const UNIX_EPOCH: DateTime
pub const UNIX_EPOCH: DateTime
The Unix epoch, 1970-01-01T00:00:00Z.
Sourcepub fn from_unix(seconds: i64) -> Result<DateTime, Error>
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.
Sourcepub fn from_unix_nanos(nanoseconds: i128) -> Result<DateTime, Error>
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.
Sourcepub fn from_parts(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanosecond: u32,
zone: TimeZone,
) -> Result<DateTime, Error>
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.
Sourcepub 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>
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).
Sourcepub fn now() -> DateTime
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.
Sourcepub fn parse_with_timezone(
input: &str,
zone: TimeZone,
) -> Result<DateTime, Error>
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.
Sourcepub fn parse_bytes(input: &[u8]) -> Result<DateTime, Error>
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.
Sourcepub fn parse_bytes_with_timezone(
input: &[u8],
zone: TimeZone,
) -> Result<DateTime, Error>
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.
Sourcepub fn parse_bytes_with_format(
input: &[u8],
format: Format,
) -> Result<DateTime, Error>
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.
Sourcepub fn format(&self, format: Format) -> Formatted<'_>
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.
Sourcepub fn try_format(&self, format: Format) -> Result<Formatted<'_>, Error>
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.
Sourcepub fn format_to(
&self,
buffer: &mut [u8],
format: Format,
) -> Result<usize, Error>
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.
Sourcepub const fn unix_nanos(&self) -> i128
pub const fn unix_nanos(&self) -> i128
Returns the number of nanoseconds since the Unix epoch.
Sourcepub const fn timezone_name(&self) -> Option<&'static str>
pub const fn timezone_name(&self) -> Option<&'static str>
Returns the canonical name of the time zone, if it has one.
Sourcepub fn in_timezone(&self, zone: TimeZone) -> DateTime
pub fn in_timezone(&self, zone: TimeZone) -> DateTime
Returns the local time at this instant in zone.
Sourcepub fn nanosecond(&self) -> u32
pub fn nanosecond(&self) -> u32
Returns the nanosecond (0..1_000_000_000).
Sourcepub fn millisecond(&self) -> u32
pub fn millisecond(&self) -> u32
Returns the millisecond (0..1000).
Sourcepub fn microsecond(&self) -> u32
pub fn microsecond(&self) -> u32
Returns the microsecond (0..1_000_000).
Sourcepub fn saturating_add(&self, duration: Duration) -> DateTime
pub fn saturating_add(&self, duration: Duration) -> DateTime
Adds a duration, saturating at the supported range boundaries.
Sourcepub fn saturating_sub(&self, duration: Duration) -> DateTime
pub fn saturating_sub(&self, duration: Duration) -> DateTime
Subtracts a duration, saturating at the supported range boundaries.
Sourcepub fn duration_since(&self, earlier: DateTime) -> Result<Duration, Error>
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.
Sourcepub fn duration_until(&self, later: DateTime) -> Result<Duration, Error>
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.
Sourcepub fn signed_duration_since(&self, other: DateTime) -> (i64, u32)
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).
Sourcepub fn elapsed(&self) -> Result<Duration, Error>
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).
Sourcepub const fn has_monotonic(&self) -> bool
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.
Sourcepub fn abbreviation(&self) -> Option<&'static str>
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).
Sourcepub fn zone_bounds(&self) -> (Option<DateTime>, Option<DateTime>)
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.
Sourcepub fn add_days(&self, days: i64) -> Result<DateTime, Error>
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.
Trait Implementations§
Source§impl AddAssign<Duration> for DateTime
impl AddAssign<Duration> for DateTime
Source§fn add_assign(&mut self, rhs: Duration)
fn add_assign(&mut self, rhs: Duration)
+= operation. Read moreimpl Copy for DateTime
Source§impl<'de> Deserialize<'de> for DateTime
impl<'de> Deserialize<'de> for DateTime
Source§fn deserialize<D>(deserializer: D) -> Result<DateTime, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<DateTime, D::Error>where
D: Deserializer<'de>,
impl Eq for DateTime
Source§impl From<DateTime> for SystemTime
Available on crate feature std only.
impl From<DateTime> for SystemTime
std only.Source§fn from(dt: DateTime) -> SystemTime
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 Ord for DateTime
impl Ord for DateTime
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
1.21.0 (const: unstable) · Source§fn min(self, other: Self) -> Selfwhere
Self: Sized,
fn min(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialOrd for DateTime
impl PartialOrd for DateTime
Source§impl SubAssign<Duration> for DateTime
impl SubAssign<Duration> for DateTime
Source§fn sub_assign(&mut self, rhs: Duration)
fn sub_assign(&mut self, rhs: Duration)
-= operation. Read moreSource§impl TryFrom<SystemTime> for DateTime
Available on crate feature std only.
impl TryFrom<SystemTime> for DateTime
std only.