#[cfg(feature = "formatting")]
use alloc::string::String;
use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::time::Duration as StdDuration;
#[cfg(feature = "formatting")]
use std::io;
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::{
carry, 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(Date::UNIX_EPOCH, 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")]
#[inline]
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"
)))]
std::time::SystemTime::now().into()
}
#[inline]
pub const fn new(date: Date, time: Time) -> Self {
Self {
inner: PrimitiveDateTime::new(date, time),
}
}
#[inline]
pub(crate) const fn from_primitive(date_time: PrimitiveDateTime) -> Self {
Self { inner: date_time }
}
#[inline]
pub(crate) const fn as_primitive(self) -> PrimitiveDateTime {
self.inner
}
#[inline]
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_t::<i64>(Day)) as i32,
)
};
let seconds_within_day = timestamp.rem_euclid(Second::per_t::<i64>(Day));
let time = unsafe {
Time::__from_hms_nanos_unchecked(
(seconds_within_day / Second::per_t::<i64>(Hour)) as u8,
((seconds_within_day % Second::per_t::<i64>(Hour)) / Minute::per_t::<i64>(Hour))
as u8,
(seconds_within_day % Second::per_t::<i64>(Minute)) as u8,
0,
)
};
Ok(Self::new(date, time))
}
#[inline]
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_t::<i128>(Second)
) as i64));
Ok(Self::new(
datetime.date(),
unsafe {
Time::__from_hms_nanos_unchecked(
datetime.hour(),
datetime.minute(),
datetime.second(),
timestamp.rem_euclid(Nanosecond::per_t(Second)) as u32,
)
},
))
}
#[inline]
#[track_caller]
pub const fn to_offset(self, offset: UtcOffset) -> OffsetDateTime {
expect_opt!(
self.checked_to_offset(offset),
"local datetime out of valid range"
)
}
#[inline]
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,
))
}
#[inline]
pub(crate) const fn to_offset_raw(self, offset: UtcOffset) -> (i32, u16, Time) {
let (second, carry) = carry!(@most_once
self.second() as i8 + offset.seconds_past_minute(),
0..Second::per_t(Minute)
);
let (minute, carry) = carry!(@most_once
self.minute() as i8 + offset.minutes_past_hour() + carry,
0..Minute::per_t(Hour)
);
let (hour, carry) = carry!(@most_twice
self.hour() as i8 + offset.whole_hours() + carry,
0..Hour::per_t(Day)
);
let (mut year, ordinal) = self.to_ordinal_date();
let mut ordinal = ordinal as i16 + carry;
cascade!(ordinal => year);
debug_assert!(ordinal > 0);
debug_assert!(ordinal <= util::days_in_year(year) as i16);
(
year,
ordinal as u16,
unsafe {
Time::__from_hms_nanos_unchecked(
hour as u8,
minute as u8,
second as u8,
self.nanosecond(),
)
},
)
}
#[inline]
pub const fn unix_timestamp(self) -> i64 {
let days = (self.to_julian_day() as i64 - UNIX_EPOCH_JULIAN_DAY as i64)
* Second::per_t::<i64>(Day);
let hours = self.hour() as i64 * Second::per_t::<i64>(Hour);
let minutes = self.minute() as i64 * Second::per_t::<i64>(Minute);
let seconds = self.second() as i64;
days + hours + minutes + seconds
}
#[inline]
pub const fn unix_timestamp_nanos(self) -> i128 {
self.unix_timestamp() as i128 * Nanosecond::per_t::<i128>(Second)
+ self.nanosecond() as i128
}
#[inline]
pub const fn date(self) -> Date {
self.inner.date()
}
#[inline]
pub const fn time(self) -> Time {
self.inner.time()
}
#[inline]
pub const fn year(self) -> i32 {
self.date().year()
}
#[inline]
pub const fn month(self) -> Month {
self.date().month()
}
#[inline]
pub const fn day(self) -> u8 {
self.date().day()
}
#[inline]
pub const fn ordinal(self) -> u16 {
self.date().ordinal()
}
#[inline]
pub const fn iso_week(self) -> u8 {
self.date().iso_week()
}
#[inline]
pub const fn sunday_based_week(self) -> u8 {
self.date().sunday_based_week()
}
#[inline]
pub const fn monday_based_week(self) -> u8 {
self.date().monday_based_week()
}
#[inline]
pub const fn to_calendar_date(self) -> (i32, Month, u8) {
self.date().to_calendar_date()
}
#[inline]
pub const fn to_ordinal_date(self) -> (i32, u16) {
self.date().to_ordinal_date()
}
#[inline]
pub const fn to_iso_week_date(self) -> (i32, u8, Weekday) {
self.date().to_iso_week_date()
}
#[inline]
pub const fn weekday(self) -> Weekday {
self.date().weekday()
}
#[inline]
pub const fn to_julian_day(self) -> i32 {
self.date().to_julian_day()
}
#[inline]
pub const fn as_hms(self) -> (u8, u8, u8) {
self.time().as_hms()
}
#[inline]
pub const fn as_hms_milli(self) -> (u8, u8, u8, u16) {
self.time().as_hms_milli()
}
#[inline]
pub const fn as_hms_micro(self) -> (u8, u8, u8, u32) {
self.time().as_hms_micro()
}
#[inline]
pub const fn as_hms_nano(self) -> (u8, u8, u8, u32) {
self.time().as_hms_nano()
}
#[inline]
pub const fn hour(self) -> u8 {
self.time().hour()
}
#[inline]
pub const fn minute(self) -> u8 {
self.time().minute()
}
#[inline]
pub const fn second(self) -> u8 {
self.time().second()
}
#[inline]
pub const fn millisecond(self) -> u16 {
self.time().millisecond()
}
#[inline]
pub const fn microsecond(self) -> u32 {
self.time().microsecond()
}
#[inline]
pub const fn nanosecond(self) -> u32 {
self.time().nanosecond()
}
#[inline]
pub const fn checked_add(self, duration: Duration) -> Option<Self> {
Some(Self::from_primitive(const_try_opt!(self
.inner
.checked_add(duration))))
}
#[inline]
pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
Some(Self::from_primitive(const_try_opt!(self
.inner
.checked_sub(duration))))
}
#[inline]
pub const fn saturating_add(self, duration: Duration) -> Self {
Self::from_primitive(self.inner.saturating_add(duration))
}
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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`."]
#[inline]
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 {
#[inline]
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),
)
}
#[inline]
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 {
#[inline]
pub fn parse(
input: &str,
description: &(impl Parsable + ?Sized),
) -> Result<Self, error::Parse> {
description.parse_utc_date_time(input.as_bytes())
}
#[cfg(feature = "parsing")]
#[inline]
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 = ();
#[inline]
fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
let width = smart_display::padded_width_of!(self.date(), " ", self.time(), " +00");
Metadata::new(width, self, ())
}
#[inline]
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 {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
SmartDisplay::fmt(self, f)
}
}
impl fmt::Debug for UtcDateTime {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Add<Duration> for UtcDateTime {
type Output = Self;
#[inline]
#[track_caller]
fn add(self, duration: Duration) -> Self::Output {
self.inner.add(duration).as_utc()
}
}
impl Add<StdDuration> for UtcDateTime {
type Output = Self;
#[inline]
#[track_caller]
fn add(self, duration: StdDuration) -> Self::Output {
self.inner.add(duration).as_utc()
}
}
impl AddAssign<Duration> for UtcDateTime {
#[inline]
#[track_caller]
fn add_assign(&mut self, rhs: Duration) {
self.inner.add_assign(rhs);
}
}
impl AddAssign<StdDuration> for UtcDateTime {
#[inline]
#[track_caller]
fn add_assign(&mut self, rhs: StdDuration) {
self.inner.add_assign(rhs);
}
}
impl Sub<Duration> for UtcDateTime {
type Output = Self;
#[inline]
#[track_caller]
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;
#[inline]
#[track_caller]
fn sub(self, duration: StdDuration) -> Self::Output {
Self::from_primitive(self.inner.sub(duration))
}
}
impl SubAssign<Duration> for UtcDateTime {
#[inline]
#[track_caller]
fn sub_assign(&mut self, rhs: Duration) {
self.inner.sub_assign(rhs);
}
}
impl SubAssign<StdDuration> for UtcDateTime {
#[inline]
#[track_caller]
fn sub_assign(&mut self, rhs: StdDuration) {
self.inner.sub_assign(rhs);
}
}
impl Sub for UtcDateTime {
type Output = Duration;
#[inline]
#[track_caller]
fn sub(self, rhs: Self) -> Self::Output {
self.inner.sub(rhs.inner)
}
}