Struct DateTime

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

Proleptic gregorian date and time with fast calculations of differences in date and time

This struct is primarily designed to provide fast calculations of possibly very large differences in date and time in the proleptic gregorian calendar. It is a superset of date and time structs like time::PrimitiveDateTime, time::OffsetDateTime which is limited to years ranging from -999_999 to 999_999 if the large-dates feature is activated and chrono::DateTime which is limited to years ranging from -262_144 to 262_143. Since gnu supports much larger dates, and to provide maximum possible compatibility with gnu, this struct provides support for dates ranging from approximately -583_344_214_028 years to 583_344_214_028 years which is far more than the age of the universe.

This struct implements From<OffsetDateTime> and From<PrimitiveDateTime> if the time feature is activated. If the chrono feature is activated From<DateTime> is available.

§Examples

use fundu_gnu::DateTime;

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0);
assert_eq!(date_time, DateTime::UNIX_EPOCH);

If the chrono feature is activated a chrono date and time can be converted lossless to a DateTime

use chrono::{FixedOffset, TimeZone};
use fundu_gnu::DateTime;

let chrono_date = FixedOffset::east_opt(0)
    .unwrap()
    .with_ymd_and_hms(2000, 12, 31, 23, 59, 59)
    .unwrap();
assert_eq!(
    DateTime::from(chrono_date),
    DateTime::from_gregorian_date_time(2000, 12, 31, 23, 59, 59, 0)
);

// Now with an offset
let chrono_date = FixedOffset::east_opt(2 * 3600)
    .unwrap()
    .with_ymd_and_hms(2000, 12, 31, 23, 59, 59)
    .unwrap();
assert_eq!(
    DateTime::from(chrono_date),
    DateTime::from_gregorian_date_time(2000, 12, 31, 21, 59, 59, 0)
);

And if the time feature is activated:

use time::macros::{datetime, offset};
use fundu_gnu::DateTime;

assert_eq!(
    DateTime::from(datetime!(2000-12-31 23:59:59.200_000_000)),
    DateTime::from_gregorian_date_time(2000, 12, 31, 23, 59, 59, 200_000_000)
);

// And with an offset
assert_eq!(
    DateTime::from(datetime!(2000-12-31 23:59:59.200_000_000 UTC).to_offset(offset!(-2))),
    DateTime::from_gregorian_date_time(2000, 12, 31, 21, 59, 59, 200_000_000)
);

Implementations§

Source§

impl DateTime

Source

pub const UNIX_EPOCH: Self

The DateTime of the unix epoch in UTC +0

Source

pub const fn from_gregorian_date_time( year: i64, month: u8, day: u8, hour: u8, minute: u8, second: u8, nanos: u32, ) -> Self

Create a DateTime from a given proleptic gregorian date and time

§Panics

This method panics if the input arguments are invalid. Valid ranges are:

  • 1 <= month <= 12
  • 1 <= day <= 31
  • 0 <= hour <= 23
  • 0 <= minute <= 59
  • 0 <= second <= 59
  • 0 <= nanos <= 999_999_999

Note it is not an error to specify day = 31 for example for the month 4 (April). In such a case the month is assumed to be the next month (here May) and day = 1.

In theory, the year may not exceed approximately 25_200_470_046_046_596 or -25_200_470_046_046_596 years within this function or else a panic occurs. To be sure that the year doesn’t cause overflows and returning None from other functions of DateTime, a safer range is -583_344_214_028 to 583_344_214_028 years.

§Examples
use fundu_gnu::DateTime;

assert_eq!(
    DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0),
    DateTime::UNIX_EPOCH
);

// 1972 is a leap year
let date_time = DateTime::from_gregorian_date_time(1972, 2, 29, 1, 30, 59, 700_000_000);
assert_eq!(
    date_time.to_gregorian_date_time(),
    Some((1972, 2, 29, 1, 30, 59, 700_000_000))
);

// Given 1960-4-31, the day carries over into the next month
assert_eq!(
    DateTime::from_gregorian_date_time(1960, 4, 31, 1, 30, 59, 700_000_000),
    DateTime::from_gregorian_date_time(1960, 5, 1, 1, 30, 59, 700_000_000),
);
Source

pub fn to_gregorian_date(&self) -> Option<(i64, u8, u8)>

Return the proleptic gregorian date

§Examples
use fundu_gnu::DateTime;

assert_eq!(DateTime::UNIX_EPOCH.to_gregorian_date(), Some((1970, 1, 1)));
assert_eq!(
    DateTime::from_gregorian_date_time(1959, 1, 12, 10, 3, 59, 0).to_gregorian_date(),
    Some((1959, 1, 12))
);
Source

pub fn to_gregorian_date_time(&self) -> Option<(i64, u8, u8, u8, u8, u8, u32)>

Return the proleptic gregorian date and time

§Examples
use fundu_gnu::DateTime;

assert_eq!(
    DateTime::UNIX_EPOCH.to_gregorian_date_time(),
    Some((1970, 1, 1, 0, 0, 0, 0))
);
assert_eq!(
    DateTime::from_gregorian_date_time(1959, 1, 12, 10, 3, 59, 500_000_000)
        .to_gregorian_date_time(),
    Some((1959, 1, 12, 10, 3, 59, 500_000_000))
);
Source

pub const fn as_hmsn(&self) -> (u8, u8, u8, u32)

Return the time as tuple with (hour, minute, second, nanos)

This method cannot fail

§Examples
use fundu_gnu::DateTime;

assert_eq!(DateTime::UNIX_EPOCH.as_hmsn(), (0, 0, 0, 0));
assert_eq!(
    DateTime::from_gregorian_date_time(1959, 1, 12, 10, 3, 59, 500_000_000).as_hmsn(),
    (10, 3, 59, 500_000_000)
);
Source

pub const fn as_julian_day(&self) -> JulianDay

Return the proleptic gregorian date as JulianDay

This JulianDay implementation does not have a fraction and returns the day as if no time was specified which is equivalent of a time being always noon

§Examples
use fundu_gnu::{DateTime, JulianDay};

assert_eq!(DateTime::UNIX_EPOCH.as_julian_day(), JulianDay(2_440_588));
assert_eq!(
    DateTime::from_gregorian_date_time(-4713, 11, 24, 10, 3, 59, 500_000_000).as_julian_day(),
    JulianDay(0)
);
assert_eq!(
    DateTime::from_gregorian_date_time(2023, 3, 9, 23, 59, 59, 999_999_999).as_julian_day(),
    JulianDay(2460013)
);
Source

pub fn now_utc() -> Self

Return the current DateTime with an offset of UTC +-0

§Platform-specific behavior

This method is subject to the same restrictions as SystemTime does.

§Examples
use fundu_gnu::DateTime;

let now = DateTime::now_utc();
Source

pub fn checked_add_duration(self, duration: &Duration) -> Option<Self>

Add a Duration to the DateTime returning some new DateTime or None on overflow

§Examples
use fundu_gnu::{DateTime, Duration};

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 23, 59, 59, 0);
assert_eq!(
    date_time.checked_add_duration(&Duration::positive(3600, 0)),
    Some(DateTime::from_gregorian_date_time(1970, 1, 2, 0, 59, 59, 0))
);
Source

pub fn checked_sub_duration(self, duration: &Duration) -> Option<Self>

Subtract a Duration from the DateTime

This method returns some new DateTime or None on overflow

§Examples
use fundu_gnu::{DateTime, Duration};

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0);
assert_eq!(
    date_time.checked_sub_duration(&Duration::positive(3600, 0)),
    Some(DateTime::from_gregorian_date_time(
        1969, 12, 31, 23, 0, 0, 0
    ))
);
Source

pub fn checked_add_gregorian( self, years: i64, months: i64, days: i64, ) -> Option<Self>

Add years, months and days to the DateTime in the proleptic gregorian calendar

This method returns some new DateTime or None on overflow

§Examples
use fundu_gnu::{DateTime, Duration};

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0);
assert_eq!(
    date_time.checked_add_gregorian(2000, 0, 0),
    Some(DateTime::from_gregorian_date_time(3970, 1, 1, 0, 0, 0, 0))
);

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0);
assert_eq!(
    date_time.checked_add_gregorian(0, 121, 0),
    Some(DateTime::from_gregorian_date_time(1980, 2, 1, 0, 0, 0, 0))
);

let date_time = DateTime::from_gregorian_date_time(1970, 1, 1, 0, 0, 0, 0);
assert_eq!(
    date_time.checked_add_gregorian(0, 0, 365),
    Some(DateTime::from_gregorian_date_time(1971, 1, 1, 0, 0, 0, 0))
);

// 1972 is a leap year
let date_time = DateTime::from_gregorian_date_time(1972, 1, 1, 0, 0, 0, 0);
assert_eq!(
    date_time.checked_add_gregorian(0, 0, 366),
    Some(DateTime::from_gregorian_date_time(1973, 1, 1, 0, 0, 0, 0))
);
Source

pub fn duration_since(self, rhs: Self) -> Option<Duration>

Calculate the Duration between this DateTime and another DateTime

If the other DateTime is greater than this DateTime the Duration is negative. This method returns None when an overflow occurs.

§Examples
use fundu_gnu::{DateTime, Duration};

let dt = DateTime::from_gregorian_date_time(1971, 1, 1, 23, 0, 0, 0);
assert_eq!(
    dt.duration_since(DateTime::UNIX_EPOCH),
    Some(Duration::positive(365 * 86400 + 23 * 3600, 0))
);

let dt = DateTime::from_gregorian_date_time(1973, 1, 1, 0, 0, 10, 123_456_789);
let other = DateTime::from_gregorian_date_time(1972, 1, 1, 0, 0, 0, 0);
assert_eq!(
    dt.duration_since(other),
    Some(Duration::positive(366 * 86400 + 10, 123_456_789))
);
assert_eq!(
    other.duration_since(dt),
    Some(Duration::negative(366 * 86400 + 10, 123_456_789))
);

Trait Implementations§

Source§

impl Clone for DateTime

Source§

fn clone(&self) -> DateTime

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 DateTime

Source§

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

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

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

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

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

impl<T: TimeZone> From<DateTime<T>> for DateTime

Available on crate feature chrono only.
Source§

fn from(value: DateTime<T>) -> Self

Converts to this type from the input type.
Source§

impl From<NaiveDateTime> for DateTime

Available on crate feature chrono only.
Source§

fn from(value: NaiveDateTime) -> Self

Converts to this type from the input type.
Source§

impl From<OffsetDateTime> for DateTime

Available on crate feature time only.
Source§

fn from(value: OffsetDateTime) -> Self

Converts to this type from the input type.
Source§

impl From<PrimitiveDateTime> for DateTime

Available on crate feature time only.
Source§

fn from(value: PrimitiveDateTime) -> Self

Converts to this type from the input type.
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 · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

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

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

impl PartialEq for DateTime

Source§

fn eq(&self, other: &DateTime) -> 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 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 · 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 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 Copy for DateTime

Source§

impl Eq for DateTime

Source§

impl StructuralPartialEq for DateTime

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