#[cfg(feature = "formatting")]
use alloc::string::String;
use core::cmp::Ordering;
use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::time::Duration as StdDuration;
#[cfg(feature = "formatting")]
use std::io;
#[cfg(feature = "std")]
use std::time::SystemTime;
use deranged::RangedI64;
use powerfmt::ext::FormatterExt as _;
use powerfmt::smart_display::{self, FormatterOptions, Metadata, SmartDisplay};
use crate::convert::*;
use crate::date::{MAX_YEAR, MIN_YEAR};
#[cfg(feature = "formatting")]
use crate::formatting::Formattable;
use crate::internal_macros::{
cascade, const_try, const_try_opt, div_floor, ensure_ranged, expect_opt,
};
#[cfg(feature = "parsing")]
use crate::parsing::Parsable;
use crate::{
error, util, Date, Duration, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday,
};
const UNIX_EPOCH_JULIAN_DAY: i32 = UtcDateTime::UNIX_EPOCH.to_julian_day();
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UtcDateTime {
inner: PrimitiveDateTime,
}
impl UtcDateTime {
pub const UNIX_EPOCH: Self = Self::new(
unsafe { Date::__from_ordinal_date_unchecked(1970, 1) },
Time::MIDNIGHT,
);
#[cfg_attr(
feature = "large-dates",
doc = "// Assuming `large-dates` feature is enabled."
)]
#[cfg_attr(
feature = "large-dates",
doc = "assert_eq!(UtcDateTime::MIN, utc_datetime!(-999999-01-01 0:00));"
)]
#[cfg_attr(
not(feature = "large-dates"),
doc = "// Assuming `large-dates` feature is disabled."
)]
#[cfg_attr(
not(feature = "large-dates"),
doc = "assert_eq!(UtcDateTime::MIN, utc_datetime!(-9999-01-01 0:00));"
)]
pub const MIN: Self = Self::new(Date::MIN, Time::MIDNIGHT);
#[cfg_attr(
feature = "large-dates",
doc = "// Assuming `large-dates` feature is enabled."
)]
#[cfg_attr(
feature = "large-dates",
doc = "assert_eq!(UtcDateTime::MAX, utc_datetime!(+999999-12-31 23:59:59.999_999_999));"
)]
#[cfg_attr(
not(feature = "large-dates"),
doc = "// Assuming `large-dates` feature is disabled."
)]
#[cfg_attr(
not(feature = "large-dates"),
doc = "assert_eq!(UtcDateTime::MAX, utc_datetime!(+9999-12-31 23:59:59.999_999_999));"
)]
pub const MAX: Self = Self::new(Date::MAX, Time::MAX);
#[cfg(feature = "std")]
pub fn now() -> Self {
#[cfg(all(
target_family = "wasm",
not(any(target_os = "emscripten", target_os = "wasi")),
feature = "wasm-bindgen"
))]
{
js_sys::Date::new_0().into()
}
#[cfg(not(all(
target_family = "wasm",
not(any(target_os = "emscripten", target_os = "wasi")),
feature = "wasm-bindgen"
)))]
SystemTime::now().into()
}
pub const fn new(date: Date, time: Time) -> Self {
Self {
inner: PrimitiveDateTime::new(date, time),
}
}
pub(crate) const fn from_primitive(date_time: PrimitiveDateTime) -> Self {
Self { inner: date_time }
}
pub const fn from_unix_timestamp(timestamp: i64) -> Result<Self, error::ComponentRange> {
type Timestamp =
RangedI64<{ UtcDateTime::MIN.unix_timestamp() }, { UtcDateTime::MAX.unix_timestamp() }>;
ensure_ranged!(Timestamp: timestamp);
let date = unsafe {
Date::from_julian_day_unchecked(
UNIX_EPOCH_JULIAN_DAY + div_floor!(timestamp, Second::per(Day) as i64) as i32,
)
};
let seconds_within_day = timestamp.rem_euclid(Second::per(Day) as _);
let time = unsafe {
Time::__from_hms_nanos_unchecked(
(seconds_within_day / Second::per(Hour) as i64) as _,
((seconds_within_day % Second::per(Hour) as i64) / Minute::per(Hour) as i64) as _,
(seconds_within_day % Second::per(Minute) as i64) as _,
0,
)
};
Ok(Self::new(date, time))
}
pub const fn from_unix_timestamp_nanos(timestamp: i128) -> Result<Self, error::ComponentRange> {
let datetime = const_try!(Self::from_unix_timestamp(div_floor!(
timestamp,
Nanosecond::per(Second) as i128
) as i64));
Ok(Self::new(
datetime.date(),
unsafe {
Time::__from_hms_nanos_unchecked(
datetime.hour(),
datetime.minute(),
datetime.second(),
timestamp.rem_euclid(Nanosecond::per(Second) as _) as u32,
)
},
))
}
pub const fn to_offset(self, offset: UtcOffset) -> OffsetDateTime {
expect_opt!(
self.checked_to_offset(offset),
"local datetime out of valid range"
)
}
pub const fn checked_to_offset(self, offset: UtcOffset) -> Option<OffsetDateTime> {
if offset.is_utc() {
return Some(self.inner.assume_utc());
}
let (year, ordinal, time) = self.to_offset_raw(offset);
if year > MAX_YEAR || year < MIN_YEAR {
return None;
}
Some(OffsetDateTime::new_in_offset(
unsafe { Date::__from_ordinal_date_unchecked(year, ordinal) },
time,
offset,
))
}
pub(crate) const fn to_offset_raw(self, offset: UtcOffset) -> (i32, u16, Time) {
let mut second = self.second() as i16 + offset.seconds_past_minute() as i16;
let mut minute = self.minute() as i16 + offset.minutes_past_hour() as i16;
let mut hour = self.hour() as i8 + offset.whole_hours();
let (mut year, ordinal) = self.to_ordinal_date();
let mut ordinal = ordinal as i16;
cascade!(second in 0..Second::per(Minute) as i16 => minute);
cascade!(minute in 0..Minute::per(Hour) as i16 => hour);
cascade!(hour in 0..Hour::per(Day) as i8 => ordinal);
cascade!(ordinal => year);
debug_assert!(ordinal > 0);
debug_assert!(ordinal <= util::days_in_year(year) as i16);
(
year,
ordinal as _,
unsafe {
Time::__from_hms_nanos_unchecked(
hour as _,
minute as _,
second as _,
self.nanosecond(),
)
},
)
}
pub const fn unix_timestamp(self) -> i64 {
let days =
(self.to_julian_day() as i64 - UNIX_EPOCH_JULIAN_DAY as i64) * Second::per(Day) as i64;
let hours = self.hour() as i64 * Second::per(Hour) as i64;
let minutes = self.minute() as i64 * Second::per(Minute) as i64;
let seconds = self.second() as i64;
days + hours + minutes + seconds
}
pub const fn unix_timestamp_nanos(self) -> i128 {
self.unix_timestamp() as i128 * Nanosecond::per(Second) as i128 + self.nanosecond() as i128
}
pub const fn date(self) -> Date {
self.inner.date()
}
pub const fn time(self) -> Time {
self.inner.time()
}
pub const fn year(self) -> i32 {
self.date().year()
}
pub const fn month(self) -> Month {
self.date().month()
}
pub const fn day(self) -> u8 {
self.date().day()
}
pub const fn ordinal(self) -> u16 {
self.date().ordinal()
}
pub const fn iso_week(self) -> u8 {
self.date().iso_week()
}
pub const fn sunday_based_week(self) -> u8 {
self.date().sunday_based_week()
}
pub const fn monday_based_week(self) -> u8 {
self.date().monday_based_week()
}
pub const fn to_calendar_date(self) -> (i32, Month, u8) {
self.date().to_calendar_date()
}
pub const fn to_ordinal_date(self) -> (i32, u16) {
self.date().to_ordinal_date()
}
pub const fn to_iso_week_date(self) -> (i32, u8, Weekday) {
self.date().to_iso_week_date()
}
pub const fn weekday(self) -> Weekday {
self.date().weekday()
}
pub const fn to_julian_day(self) -> i32 {
self.date().to_julian_day()
}
pub const fn as_hms(self) -> (u8, u8, u8) {
self.time().as_hms()
}
pub const fn as_hms_milli(self) -> (u8, u8, u8, u16) {
self.time().as_hms_milli()
}
pub const fn as_hms_micro(self) -> (u8, u8, u8, u32) {
self.time().as_hms_micro()
}
pub const fn as_hms_nano(self) -> (u8, u8, u8, u32) {
self.time().as_hms_nano()
}
pub const fn hour(self) -> u8 {
self.time().hour()
}
pub const fn minute(self) -> u8 {
self.time().minute()
}
pub const fn second(self) -> u8 {
self.time().second()
}
pub const fn millisecond(self) -> u16 {
self.time().millisecond()
}
pub const fn microsecond(self) -> u32 {
self.time().microsecond()
}
pub const fn nanosecond(self) -> u32 {
self.time().nanosecond()
}
pub const fn checked_add(self, duration: Duration) -> Option<Self> {
Some(Self::from_primitive(const_try_opt!(self
.inner
.checked_add(duration))))
}
pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
Some(Self::from_primitive(const_try_opt!(self
.inner
.checked_sub(duration))))
}
pub const fn saturating_add(self, duration: Duration) -> Self {
Self::from_primitive(self.inner.saturating_add(duration))
}
pub const fn saturating_sub(self, duration: Duration) -> Self {
Self::from_primitive(self.inner.saturating_sub(duration))
}
}
impl UtcDateTime {
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_time(self, time: Time) -> Self {
Self::from_primitive(self.inner.replace_time(time))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_date(self, date: Date) -> Self {
Self::from_primitive(self.inner.replace_date(date))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_year(self, year: i32) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_year(year))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_month(self, month: Month) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_month(month))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_day(self, day: u8) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_day(day))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_ordinal(self, ordinal: u16) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_ordinal(ordinal))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_hour(self, hour: u8) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_hour(hour))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_minute(
self,
sunday_based_week: u8,
) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_minute(sunday_based_week))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_second(
self,
monday_based_week: u8,
) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_second(monday_based_week))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_millisecond(
self,
millisecond: u16,
) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_millisecond(millisecond))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_microsecond(
self,
microsecond: u32,
) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_microsecond(microsecond))))
}
#[must_use = "This method does not mutate the original `UtcDateTime`."]
pub const fn replace_nanosecond(self, nanosecond: u32) -> Result<Self, error::ComponentRange> {
Ok(Self::from_primitive(const_try!(self
.inner
.replace_nanosecond(nanosecond))))
}
}
#[cfg(feature = "formatting")]
impl UtcDateTime {
pub fn format_into(
self,
output: &mut (impl io::Write + ?Sized),
format: &(impl Formattable + ?Sized),
) -> Result<usize, error::Format> {
format.format_into(
output,
Some(self.date()),
Some(self.time()),
Some(UtcOffset::UTC),
)
}
pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
format.format(Some(self.date()), Some(self.time()), Some(UtcOffset::UTC))
}
}
#[cfg(feature = "parsing")]
impl UtcDateTime {
pub fn parse(
input: &str,
description: &(impl Parsable + ?Sized),
) -> Result<Self, error::Parse> {
description.parse_utc_date_time(input.as_bytes())
}
#[cfg(feature = "parsing")]
pub(crate) const fn is_valid_leap_second_stand_in(self) -> bool {
let dt = self.inner;
dt.hour() == 23
&& dt.minute() == 59
&& dt.second() == 59
&& dt.nanosecond() == 999_999_999
&& dt.day() == dt.month().length(dt.year())
}
}
impl SmartDisplay for UtcDateTime {
type Metadata = ();
fn metadata(&self, _: FormatterOptions) -> Metadata<Self> {
let width = smart_display::padded_width_of!(self.date(), " ", self.time(), " +00");
Metadata::new(width, self, ())
}
fn fmt_with_metadata(
&self,
f: &mut fmt::Formatter<'_>,
metadata: Metadata<Self>,
) -> fmt::Result {
f.pad_with_width(
metadata.unpadded_width(),
format_args!("{} {} +00", self.date(), self.time()),
)
}
}
impl fmt::Display for UtcDateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
SmartDisplay::fmt(self, f)
}
}
impl fmt::Debug for UtcDateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Add<Duration> for UtcDateTime {
type Output = Self;
fn add(self, duration: Duration) -> Self::Output {
self.inner.add(duration).as_utc()
}
}
impl Add<StdDuration> for UtcDateTime {
type Output = Self;
fn add(self, duration: StdDuration) -> Self::Output {
self.inner.add(duration).as_utc()
}
}
impl AddAssign<Duration> for UtcDateTime {
fn add_assign(&mut self, rhs: Duration) {
self.inner.add_assign(rhs);
}
}
impl AddAssign<StdDuration> for UtcDateTime {
fn add_assign(&mut self, rhs: StdDuration) {
self.inner.add_assign(rhs);
}
}
impl Sub<Duration> for UtcDateTime {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
self.checked_sub(rhs)
.expect("resulting value is out of range")
}
}
impl Sub<StdDuration> for UtcDateTime {
type Output = Self;
fn sub(self, duration: StdDuration) -> Self::Output {
Self::from_primitive(self.inner.sub(duration))
}
}
impl SubAssign<Duration> for UtcDateTime {
fn sub_assign(&mut self, rhs: Duration) {
self.inner.sub_assign(rhs);
}
}
impl SubAssign<StdDuration> for UtcDateTime {
fn sub_assign(&mut self, rhs: StdDuration) {
self.inner.sub_assign(rhs);
}
}
impl Sub for UtcDateTime {
type Output = Duration;
fn sub(self, rhs: Self) -> Self::Output {
self.inner.sub(rhs.inner)
}
}
#[cfg(feature = "std")]
impl Sub<SystemTime> for UtcDateTime {
type Output = Duration;
fn sub(self, rhs: SystemTime) -> Self::Output {
self - Self::from(rhs)
}
}
#[cfg(feature = "std")]
impl Sub<UtcDateTime> for SystemTime {
type Output = Duration;
fn sub(self, rhs: UtcDateTime) -> Self::Output {
UtcDateTime::from(self) - rhs
}
}
impl Sub<OffsetDateTime> for UtcDateTime {
type Output = Duration;
fn sub(self, rhs: OffsetDateTime) -> Self::Output {
OffsetDateTime::from(self) - rhs
}
}
impl Sub<UtcDateTime> for OffsetDateTime {
type Output = Duration;
fn sub(self, rhs: UtcDateTime) -> Self::Output {
self - Self::from(rhs)
}
}
#[cfg(feature = "std")]
impl PartialEq<SystemTime> for UtcDateTime {
fn eq(&self, rhs: &SystemTime) -> bool {
self == &Self::from(*rhs)
}
}
#[cfg(feature = "std")]
impl PartialEq<UtcDateTime> for SystemTime {
fn eq(&self, rhs: &UtcDateTime) -> bool {
&UtcDateTime::from(*self) == rhs
}
}
impl PartialEq<OffsetDateTime> for UtcDateTime {
fn eq(&self, other: &OffsetDateTime) -> bool {
OffsetDateTime::from(*self) == *other
}
}
impl PartialEq<UtcDateTime> for OffsetDateTime {
fn eq(&self, other: &UtcDateTime) -> bool {
*self == Self::from(*other)
}
}
#[cfg(feature = "std")]
impl PartialOrd<SystemTime> for UtcDateTime {
fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering> {
self.partial_cmp(&Self::from(*other))
}
}
#[cfg(feature = "std")]
impl PartialOrd<UtcDateTime> for SystemTime {
fn partial_cmp(&self, other: &UtcDateTime) -> Option<Ordering> {
UtcDateTime::from(*self).partial_cmp(other)
}
}
impl PartialOrd<OffsetDateTime> for UtcDateTime {
fn partial_cmp(&self, other: &OffsetDateTime) -> Option<Ordering> {
OffsetDateTime::from(*self).partial_cmp(other)
}
}
impl PartialOrd<UtcDateTime> for OffsetDateTime {
fn partial_cmp(&self, other: &UtcDateTime) -> Option<Ordering> {
self.partial_cmp(&Self::from(*other))
}
}
#[cfg(feature = "std")]
impl From<SystemTime> for UtcDateTime {
fn from(system_time: SystemTime) -> Self {
match system_time.duration_since(SystemTime::UNIX_EPOCH) {
Ok(duration) => Self::UNIX_EPOCH + duration,
Err(err) => Self::UNIX_EPOCH - err.duration(),
}
}
}
#[cfg(feature = "std")]
impl From<UtcDateTime> for SystemTime {
fn from(datetime: UtcDateTime) -> Self {
let duration = datetime - UtcDateTime::UNIX_EPOCH;
if duration.is_zero() {
Self::UNIX_EPOCH
} else if duration.is_positive() {
Self::UNIX_EPOCH + duration.unsigned_abs()
} else {
debug_assert!(duration.is_negative());
Self::UNIX_EPOCH - duration.unsigned_abs()
}
}
}
impl From<OffsetDateTime> for UtcDateTime {
fn from(datetime: OffsetDateTime) -> Self {
datetime.to_utc()
}
}
impl From<UtcDateTime> for OffsetDateTime {
fn from(datetime: UtcDateTime) -> Self {
datetime.inner.assume_utc()
}
}
#[cfg(all(
target_family = "wasm",
not(any(target_os = "emscripten", target_os = "wasi")),
feature = "wasm-bindgen"
))]
impl From<js_sys::Date> for UtcDateTime {
fn from(js_date: js_sys::Date) -> Self {
let timestamp_nanos = (js_date.get_time() * Nanosecond::per(Millisecond) as f64) as i128;
Self::from_unix_timestamp_nanos(timestamp_nanos)
.expect("invalid timestamp: Timestamp cannot fit in range")
}
}
#[cfg(all(
target_family = "wasm",
not(any(target_os = "emscripten", target_os = "wasi")),
feature = "wasm-bindgen"
))]
impl From<UtcDateTime> for js_sys::Date {
fn from(datetime: UtcDateTime) -> Self {
let timestamp = (datetime.unix_timestamp_nanos()
/ Nanosecond::per(Millisecond).cast_signed().extend::<i128>())
as f64;
Self::new(×tamp.into())
}
}