Struct Date
struct Date { ... }
A representation of a civil date in the Gregorian calendar.
A Date value corresponds to a triple of year, month and day. Every Date
value is guaranteed to be a valid Gregorian calendar date. For example,
both 2023-02-29 and 2023-11-31 are invalid and cannot be represented by
a Date.
Civil dates
A Date value behaves without regard to daylight saving time or time
zones in general. When doing arithmetic on dates with spans defined in
units of time (such as with Date::checked_add), days are considered to
always be precisely 86,400 seconds long.
Parsing and printing
The Date type provides convenient trait implementations of
std::str::FromStr and [std::fmt::Display]:
use Date;
let date: Date = "2024-06-19".parse?;
assert_eq!;
# Ok::
A civil Date can also be parsed from something that contains a date,
but with perhaps other data (such as an offset or time zone):
use Date;
let date: Date = "2024-06-19T15:22:45-04[America/New_York]".parse?;
assert_eq!;
# Ok::
For more information on the specific format supported, see the
fmt::temporal module documentation.
Default value
For convenience, this type implements the Default trait. Its default
value corresponds to 0000-01-01. One can also access this value via the
Date::ZERO constant.
Comparisons
The Date type provides both Eq and Ord trait implementations to
facilitate easy comparisons. When a date d1 occurs before a date d2,
then d1 < d2. For example:
use date;
let d1 = date;
let d2 = date;
assert!;
Arithmetic
This type provides routines for adding and subtracting spans of time, as
well as computing the span of time between two Date values.
For adding or subtracting spans of time, one can use any of the following routines:
Date::checked_addorDate::checked_subfor checked arithmetic.Date::saturating_addorDate::saturating_subfor saturating arithmetic.
Additionally, checked arithmetic is available via the Add and Sub
trait implementations. When the result overflows, a panic occurs.
use ;
let start = date;
let one_week_later = start + 1.weeks;
assert_eq!;
One can compute the span of time between two dates using either
Date::until or Date::since. It's also possible to subtract two
Date values directly via a Sub trait implementation:
use ;
let date1 = date;
let date2 = date;
assert_eq!;
The until and since APIs are polymorphic and allow re-balancing and
rounding the span returned. For example, the default largest unit is days
(as exemplified above), but we can ask for bigger units:
use ;
let date1 = date;
let date2 = date;
assert_eq!;
# Ok::
Or even round the span returned:
use ;
let date1 = date;
let date2 = date;
assert_eq!;
// `DateDifference` uses truncation as a rounding mode by default,
// but you can set the rounding mode to break ties away from zero:
assert_eq!;
# Ok::
Rounding
Rounding dates is currently not supported. If you want this functionality, please participate in the issue tracking its support.
Implementations
impl Date
fn new(year: i16, month: i8, day: i8) -> Result<Date, Error>Creates a new
Datevalue from its component year, month and day values.To set the component values of a date after creating it, use
DateWithviaDate::withto build a newDatefrom the fields of an existing date.Errors
This returns an error when the given year-month-day does not correspond to a valid date. Namely, all of the following must be true:
- The year must be in the range
-9999..=9999. - The month must be in the range
1..=12. - The day must be at least
1and must be at most the number of days in the corresponding month. So for example,2024-02-29is valid but2023-02-29is not.
Example
This shows an example of a valid date:
use Date; let d = new.unwrap; assert_eq!; assert_eq!; assert_eq!;This shows an example of an invalid date:
use Date; assert!;- The year must be in the range
const fn constant(year: i16, month: i8, day: i8) -> DateCreates a new
Datevalue in aconstcontext.Panics
This routine panics when
Date::newwould return an error. That is, when the given year-month-day does not correspond to a valid date. Namely, all of the following must be true:- The year must be in the range
-9999..=9999. - The month must be in the range
1..=12. - The day must be at least
1and must be at most the number of days in the corresponding month. So for example,2024-02-29is valid but2023-02-29is not.
Example
use Date; let d = constant; assert_eq!; assert_eq!; assert_eq!;- The year must be in the range
fn from_iso_week_date(weekdate: ISOWeekDate) -> DateConstruct a Gregorian date from an ISO 8601 week date.
The
ISOWeekDatetype describes itself in more detail, but in breif, the ISO week date calendar system eschews months in favor of weeks.The minimum and maximum values of an
ISOWeekDatecorrespond precisely to the minimum and maximum values of aDate. Therefore, converting between them is lossless and infallible.This routine is equivalent to
ISOWeekDate::date. It is also available via aFrom<ISOWeekDate>trait implementation forDate.Example
This shows a number of examples demonstrating the conversion from an ISO 8601 week date to a Gregorian date.
use ; let weekdate = new.unwrap; let d = from_iso_week_date; assert_eq!; let weekdate = new.unwrap; let d = from_iso_week_date; assert_eq!; let weekdate = new.unwrap; let d = from_iso_week_date; assert_eq!; let weekdate = new.unwrap; let d = from_iso_week_date; assert_eq!; let weekdate = new.unwrap; let d = from_iso_week_date; assert_eq!;fn with(self: Self) -> DateWithCreate a builder for constructing a
Datefrom the fields of this date.See the methods on
DateWithfor the different ways one can set the fields of a newDate.Example
The builder ensures one can chain together the individual components of a date without it failing at an intermediate step. For example, if you had a date of
2024-10-31and wanted to change both the day and the month, and each setting was validated independent of the other, you would need to be careful to set the day first and then the month. In some cases, you would need to set the month first and then the day!But with the builder, you can set values in any order:
use date; let d1 = date; let d2 = d1.with.month.day.build?; assert_eq!; let d1 = date; let d2 = d1.with.day.month.build?; assert_eq!; # Ok::fn year(self: Self) -> i16Returns the year for this date.
The value returned is guaranteed to be in the range
-9999..=9999.Example
use date; let d1 = date; assert_eq!; let d2 = date; assert_eq!; let d3 = date; assert_eq!;fn era_year(self: Self) -> (i16, Era)Returns the year and its era.
This crate specifically allows years to be negative or
0, where as years written for the Gregorian calendar are always positive and greater than0. In the Gregorian calendar, the era labelsBCEandCEare used to disambiguate between years less than or equal to0and years greater than0, respectively.The crate is designed this way so that years in the latest era (that is,
CE) are aligned with years in this crate.The year returned is guaranteed to be in the range
1..=10000.Example
use ; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!;fn month(self: Self) -> i8Returns the month for this date.
The value returned is guaranteed to be in the range
1..=12.Example
use date; let d1 = date; assert_eq!;fn day(self: Self) -> i8Returns the day for this date.
The value returned is guaranteed to be in the range
1..=31.Example
use date; let d1 = date; assert_eq!;fn weekday(self: Self) -> WeekdayReturns the weekday corresponding to this date.
Example
use ; // The Unix epoch was on a Thursday. let d1 = date; assert_eq!; // One can also get the weekday as an offset in a variety of schemes. assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn day_of_year(self: Self) -> i16Returns the ordinal day of the year that this date resides in.
For leap years, this always returns a value in the range
1..=366. Otherwise, the value is in the range1..=365.Example
use date; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!;fn day_of_year_no_leap(self: Self) -> Option<i16>Returns the ordinal day of the year that this date resides in, but ignores leap years.
That is, the range of possible values returned by this routine is
1..=365, even if this date resides in a leap year. If this date is February 29, then this routine returnsNone.The value
365always corresponds to the last day in the year, December 31, even for leap years.Example
use date; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!;fn first_of_month(self: Self) -> DateReturns the first date of the month that this date resides in.
Example
use date; let d = date; assert_eq!;fn last_of_month(self: Self) -> DateReturns the last date of the month that this date resides in.
Example
use date; let d = date; assert_eq!;fn days_in_month(self: Self) -> i8Returns the total number of days in the the month in which this date resides.
This is guaranteed to always return one of the following values, depending on the year and the month: 28, 29, 30 or 31.
Example
use date; let d = date; assert_eq!; let d = date; assert_eq!; let d = date; assert_eq!;fn first_of_year(self: Self) -> DateReturns the first date of the year that this date resides in.
Example
use date; let d = date; assert_eq!;fn last_of_year(self: Self) -> DateReturns the last date of the year that this date resides in.
Example
use date; let d = date; assert_eq!;fn days_in_year(self: Self) -> i16Returns the total number of days in the the year in which this date resides.
This is guaranteed to always return either
365or366.Example
use date; let d = date; assert_eq!; let d = date; assert_eq!;fn in_leap_year(self: Self) -> boolReturns true if and only if the year in which this date resides is a leap year.
Example
use date; assert!; assert!;fn tomorrow(self: Self) -> Result<Date, Error>Returns the date immediately following this one.
Errors
This returns an error when this date is the maximum value.
Example
use ; let d = date; assert_eq!; // The max doesn't have a tomorrow. assert!; # Ok::fn yesterday(self: Self) -> Result<Date, Error>Returns the date immediately preceding this one.
Errors
This returns an error when this date is the minimum value.
Example
use ; let d = date; assert_eq!; // The min doesn't have a yesterday. assert!; # Ok::fn nth_weekday_of_month(self: Self, nth: i8, weekday: Weekday) -> Result<Date, Error>Returns the "nth" weekday from the beginning or end of the month in which this date resides.
The
nthparameter can be positive or negative. A positive value computes the "nth" weekday from the beginning of the month. A negative value computes the "nth" weekday from the end of the month. So for example, use-1to "find the last weekday" in this date's month.Errors
This returns an error when
nthis0, or if it is5or-5and there is no 5th weekday from the beginning or end of the month.Example
This shows how to get the nth weekday in a month, starting from the beginning of the month:
use ; let month = date; let second_friday = month.nth_weekday_of_month?; assert_eq!; # Ok::This shows how to do the reverse of the above. That is, the nth last weekday in a month:
use ; let month = date; let last_thursday = month.nth_weekday_of_month?; assert_eq!; let second_last_thursday = month.nth_weekday_of_month?; assert_eq!; # Ok::This routine can return an error if there isn't an
nthweekday for this month. For example, March 2024 only has 4 Mondays:use ; let month = date; let fourth_monday = month.nth_weekday_of_month?; assert_eq!; // There is no 5th Monday. assert!; // Same goes for counting backwards. assert!; # Ok::fn nth_weekday(self: Self, nth: i32, weekday: Weekday) -> Result<Date, Error>Returns the "nth" weekday from this date, not including itself.
The
nthparameter can be positive or negative. A positive value computes the "nth" weekday starting at the day after this date and going forwards in time. A negative value computes the "nth" weekday starting at the day before this date and going backwards in time.For example, if this date's weekday is a Sunday and the first Sunday is asked for (that is,
date.nth_weekday(1, Weekday::Sunday)), then the result is a week from this date corresponding to the following Sunday.Errors
This returns an error when
nthis0, or if it would otherwise result in a date that overflows the minimum/maximum values ofDate.Example
This example shows how to find the "nth" weekday going forwards in time:
use ; // Use a Sunday in March as our start date. let d = date; assert_eq!; // The first next Monday is tomorrow! let next_monday = d.nth_weekday?; assert_eq!; // But the next Sunday is a week away, because this doesn't // include the current weekday. let next_sunday = d.nth_weekday?; assert_eq!; // "not this Thursday, but next Thursday" let next_next_thursday = d.nth_weekday?; assert_eq!; # Ok::This example shows how to find the "nth" weekday going backwards in time:
use ; // Use a Sunday in March as our start date. let d = date; assert_eq!; // "last Saturday" was yesterday! let last_saturday = d.nth_weekday?; assert_eq!; // "last Sunday" was a week ago. let last_sunday = d.nth_weekday?; assert_eq!; // "not last Thursday, but the one before" let prev_prev_thursday = d.nth_weekday?; assert_eq!; # Ok::This example shows that overflow results in an error in either direction:
use ; let d = MAX; assert_eq!; assert!; let d = MIN; assert_eq!; assert!;Example: the start of Israeli summer time
Israeli law says (at present, as of 2024-03-11) that DST or "summer time" starts on the Friday before the last Sunday in March. We can find that date using both
nth_weekdayand [Date::nth_weekday_of_month]:use ; let march = date; let last_sunday = march.nth_weekday_of_month?; let dst_starts_on = last_sunday.nth_weekday?; assert_eq!; # Ok::Example: getting the start of the week
Given a date, one can use
nth_weekdayto determine the start of the week in which the date resides in. This might vary based on whether the weeks start on Sunday or Monday. This example shows how to handle both.use ; let d = date; // For weeks starting with Sunday. let start_of_week = d.tomorrow?.nth_weekday?; assert_eq!; // For weeks starting with Monday. let start_of_week = d.tomorrow?.nth_weekday?; assert_eq!; # Ok::In the above example, we first get the date after the current one because
nth_weekdaydoes not consider itself when counting. This works as expected even at the boundaries of a week:use ; // The start of the week. let d = date; let start_of_week = d.tomorrow?.nth_weekday?; assert_eq!; // The end of the week. let d = date; let start_of_week = d.tomorrow?.nth_weekday?; assert_eq!; # Ok::fn iso_week_date(self: Self) -> ISOWeekDateConstruct an ISO 8601 week date from this Gregorian date.
The
ISOWeekDatetype describes itself in more detail, but in brief, the ISO week date calendar system eschews months in favor of weeks.The minimum and maximum values of an
ISOWeekDatecorrespond precisely to the minimum and maximum values of aDate. Therefore, converting between them is lossless and infallible.This routine is equivalent to
ISOWeekDate::from_date.Example
This shows a number of examples demonstrating the conversion from a Gregorian date to an ISO 8601 week date:
use ; let weekdate = date.iso_week_date; assert_eq!; assert_eq!; assert_eq!; let weekdate = date.iso_week_date; assert_eq!; assert_eq!; assert_eq!; let weekdate = date.iso_week_date; assert_eq!; assert_eq!; assert_eq!; let weekdate = date.iso_week_date; assert_eq!; assert_eq!; assert_eq!; let weekdate = MIN.iso_week_date; assert_eq!; assert_eq!; assert_eq!; let weekdate = MAX.iso_week_date; assert_eq!; assert_eq!; assert_eq!;fn in_tz(self: Self, time_zone_name: &str) -> Result<Zoned, Error>Converts a civil date to a
Zoneddatetime by adding the given time zone and setting the clock time to midnight.This is a convenience function for
date.to_datetime(midnight).in_tz(name). SeeDateTime::to_zonedfor more details. Note that ambiguous datetimes are handled in the same way asDateTime::to_zoned.Errors
This returns an error when the given time zone name could not be found in the default time zone database.
This also returns an error if this date could not be represented as a timestamp. This can occur in some cases near the minimum and maximum boundaries of a
Date.Example
This is a simple example of converting a civil date (a "wall" or "local" or "naive" date) to a precise instant in time that is aware of its time zone:
use date; let zdt = date.in_tz?; assert_eq!; # Ok::Example: dealing with ambiguity
Since a
Zonedcorresponds to a precise instant in time (to nanosecond precision) and aDatecan be many possible such instants, this routine chooses one for this date: the first one, or midnight.Interestingly, some regions implement their daylight saving time transitions at midnight. This means there are some places in the world where, once a year, midnight does not exist on their clocks. As a result, it's possible for the datetime string representing a
Zonedto be something other than midnight. For example:use date; let zdt = date.in_tz?; assert_eq!; # Ok::Since this uses
Disambiguation::Compatible, and since that also chooses the "later" time in a forward transition, it follows that the date of the returnedZonedwill always match this civil date. (Unless there is a pathological time zone with a 24+ hour transition forward.)But if a different disambiguation strategy is used, even when only dealing with standard one hour transitions, the date returned can be different:
use ; let tz = get?; let dt = date.at; let zdt = tz.to_ambiguous_zoned.earlier?; assert_eq!; # Ok::fn to_zoned(self: Self, tz: TimeZone) -> Result<Zoned, Error>Converts a civil datetime to a
Zoneddatetime by adding the givenTimeZoneand setting the clock time to midnight.This is a convenience function for
date.to_datetime(midnight).to_zoned(tz). SeeDateTime::to_zonedfor more details. Note that ambiguous datetimes are handled in the same way asDateTime::to_zoned.In the common case of a time zone being represented as a name string, like
Australia/Tasmania, consider usingDate::in_tzinstead.Errors
This returns an error if this date could not be represented as a timestamp. This can occur in some cases near the minimum and maximum boundaries of a
Date.Example
This example shows how to create a zoned value with a fixed time zone offset:
use ; let tz = offset.to_time_zone; let zdt = date.to_zoned?; // A time zone annotation is still included in the printable version // of the Zoned value, but it is fixed to a particular offset. assert_eq!; # Ok::const fn to_datetime(self: Self, time: Time) -> DateTimeGiven a
Time, this constructs aDateTimevalue with its time component equal to this time.This is a convenience function for
DateTime::from_parts.Example
use ; let date = date; let time = time; assert_eq!;const fn at(self: Self, hour: i8, minute: i8, second: i8, subsec_nanosecond: i32) -> DateTimeA convenience function for constructing a
DateTimefrom this date at the time given by its components.Example
use date; assert_eq!;One can also flip the order by making use of [
Time::on]:use time; assert_eq!;fn checked_add<A: Into<DateArithmetic>>(self: Self, duration: A) -> Result<Date, Error>Add the given span of time to this date. If the sum would overflow the minimum or maximum date values, then an error is returned.
This operation accepts three different duration types:
Span,SignedDurationorstd::time::Duration. This is achieved viaFromtrait implementations for theDateArithmetictype.Properties
When adding a
Spanduration, this routine is not reversible because some additions may be ambiguous. For example, adding1 monthto the date2024-03-31will produce2024-04-30since April has only 30 days in a month. Conversely, subtracting1 monthfrom2024-04-30will produce2024-03-30, which is not the date we started with.If spans of time are limited to units of days (or less), then this routine is reversible. This also implies that all operations with a
SignedDurationor astd::time::Durationare reversible.Errors
If the span added to this date would result in a date that exceeds the range of a
Date, then this will return an error.Examples
This shows a few examples of adding spans of time to various dates. We make use of the
ToSpantrait for convenient creation of spans.use ; let d = date; assert_eq!; // Adding two months gives us May 31, not May 30. let d = date; assert_eq!; // Any time in the span that does not exceed a day is ignored. let d = date; assert_eq!; // But if the time exceeds a day, that is accounted for! let d = date; assert_eq!; # Ok::Example: available via addition operator
This routine can be used via the
+operator. Note though that if it fails, it will result in a panic.use ; let d = date; assert_eq!;Example: negative spans are supported
use ; let d = date; assert_eq!; # Ok::Example: error on overflow
use ; let d = date; assert!; assert!;Example: adding absolute durations
This shows how to add signed and unsigned absolute durations to a
Date. Only whole numbers of days are considered. Since this is a civil date unaware of time zones, days are always 24 hours.use Duration; use ; let d = date; let dur = from_hours; assert_eq!; assert_eq!; // Any leftover time is truncated. That is, only // whole days from the duration are considered. let dur = from_secs; assert_eq!; # Ok::fn checked_sub<A: Into<DateArithmetic>>(self: Self, duration: A) -> Result<Date, Error>This routine is identical to
Date::checked_addwith the duration negated.Errors
This has the same error conditions as
Date::checked_add.Example
use Duration; use ; let d = date; assert_eq!; let dur = from_hours; assert_eq!; let dur = from_secs; assert_eq!; # Ok::fn saturating_add<A: Into<DateArithmetic>>(self: Self, duration: A) -> DateThis routine is identical to
Date::checked_add, except the result saturates on overflow. That is, instead of overflow, eitherDate::MINorDate::MAXis returned.Example
use ; let d = date; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn saturating_sub<A: Into<DateArithmetic>>(self: Self, duration: A) -> DateThis routine is identical to
Date::saturating_addwith the span parameter negated.Example
use ; let d = date; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn until<A: Into<DateDifference>>(self: Self, other: A) -> Result<Span, Error>Returns a span representing the elapsed time from this date until the given
otherdate.When
otheroccurs before this date, then the span returned will be negative.Depending on the input provided, the span returned is rounded. It may also be balanced up to bigger units than the default. By default, the span returned is balanced such that the biggest and smallest possible unit is days.
This operation is configured by providing a
DateDifferencevalue. Since this routine accepts anything that implementsInto<DateDifference>, once can pass aDatedirectly. One can also pass a(Unit, Date), whereUnitis treated asDateDifference::largest.Properties
It is guaranteed that if the returned span is subtracted from
other, and if no rounding is requested, and if the largest unit request is at mostUnit::Day, then the original date will be returned.This routine is equivalent to
self.since(other).map(|span| -span)if no rounding options are set. If rounding options are set, then it's equivalent toself.since(other_without_rounding_options).map(|span| -span), followed by a call toSpan::roundwith the appropriate rounding options set. This is because the negation of a span can result in different rounding results depending on the rounding mode.Errors
An error can occur if
DateDifferenceis misconfigured. For example, if the smallest unit provided is bigger than the largest unit.It is guaranteed that if one provides a date with the default
DateDifferenceconfiguration, then this routine will never fail.Examples
use ; let earlier = date; let later = date; assert_eq!; // Flipping the dates is fine, but you'll get a negative span. let earlier = date; let later = date; assert_eq!; # Ok::Example: using bigger units
This example shows how to expand the span returned to bigger units. This makes use of a
From<(Unit, Date)> for DateDifferencetrait implementation.use ; let d1 = date; let d2 = date; // The default limits durations to using "days" as the biggest unit. let span = d1.until?; assert_eq!; // But we can ask for units all the way up to years. let span = d1.until?; assert_eq!; # Ok::Example: rounding the result
This shows how one might find the difference between two dates and have the result rounded to the nearest month.
In this case, we need to hand-construct a
DateDifferencein order to gain full configurability.use ; let d1 = date; let d2 = date; let span = d1.until?; assert_eq!; // Or even include years to make the span a bit more comprehensible. let span = d1.until?; // Notice that we are one day shy of 23y2m. Rounding spans computed // between dates uses truncation by default. assert_eq!; # Ok::Example: units biggers than days inhibit reversibility
If you ask for units bigger than days, then adding the span returned to the
otherdate is not guaranteed to result in the original date. For example:use ; let d1 = date; let d2 = date; let span = d1.until?; assert_eq!; let maybe_original = d2.checked_sub?; // Not the same as the original datetime! assert_eq!; // But in the default configuration, days are always the biggest unit // and reversibility is guaranteed. let span = d1.until?; assert_eq!; let is_original = d2.checked_sub?; assert_eq!; # Ok::This occurs because spans are added as if by adding the biggest units first, and then the smaller units. Because months vary in length, their meaning can change depending on how the span is added. In this case, adding one month to
2024-03-02corresponds to 31 days, but subtracting one month from2024-05-01corresponds to 30 days.fn since<A: Into<DateDifference>>(self: Self, other: A) -> Result<Span, Error>This routine is identical to
Date::until, but the order of the parameters is flipped.Errors
This has the same error conditions as
Date::until.Example
This routine can be used via the
-operator. Since the default configuration is used and because aSpancan represent the difference between any two possible dates, it will never panic.use ; let earlier = date; let later = date; assert_eq!; // Equivalent to: assert_eq!;fn duration_until(self: Self, other: Date) -> SignedDurationReturns an absolute duration representing the elapsed time from this date until the given
otherdate.When
otheroccurs before this date, then the duration returned will be negative.Unlike
Date::until, this returns a duration corresponding to a 96-bit integer of nanoseconds between two dates. In this case of computing durations between civil dates where all days are assumed to be 24 hours long, the duration returned will always be divisible by 24 hours. (That is,24 * 60 * 60 * 1_000_000_000nanoseconds.)Fallibility
This routine never panics or returns an error. Since there are no configuration options that can be incorrectly provided, no error is possible when calling this routine. In contrast,
Date::untilcan return an error in some cases due to misconfiguration. But like this routine,Date::untilnever panics or returns an error in its default configuration.When should I use this versus
Date::until?See the type documentation for
SignedDurationfor the section on when one should useSpanand when one should useSignedDuration. In short, useSpan(and thereforeDate::until) unless you have a specific reason to do otherwise.Example
use ; let earlier = date; let later = date; assert_eq!;Example: difference with
Date::untilThe main difference between this routine and
Date::untilis that the latter can return units other than a 96-bit integer of nanoseconds. While a 96-bit integer of nanoseconds can be converted into other units like hours, this can only be done for uniform units. (Uniform units are units for which each individual unit always corresponds to the same elapsed time regardless of the datetime it is relative to.) This can't be done for units like years, months or days without a relative date.use ; let d1 = date; let d2 = date; let span = d1.until?; assert_eq!; let duration = d1.duration_until; assert_eq!; // There's no way to extract years or months from the signed // duration like one might extract hours (because every hour // is the same length). Instead, you actually have to convert // it to a span and then balance it by providing a relative date! let options = new.largest.relative; let span = try_from?.round?; assert_eq!; # Ok::Example: getting an unsigned duration
If you're looking to find the duration between two dates as a
std::time::Duration, you'll need to use this method to get aSignedDurationand then convert it to astd::time::Duration:use Duration; use ; let d1 = date; let d2 = date; let duration = try_from?; assert_eq!; // Note that unsigned durations cannot represent all // possible differences! If the duration would be negative, // then the conversion fails: assert!; # Ok::fn duration_since(self: Self, other: Date) -> SignedDurationThis routine is identical to
Date::duration_until, but the order of the parameters is flipped.Example
use ; let earlier = date; let later = date; assert_eq!;fn series(self: Self, period: Span) -> DateSeriesReturn an iterator of periodic dates determined by the given span.
The given span may be negative, in which case, the iterator will move backwards through time. The iterator won't stop until either the span itself overflows, or it would otherwise exceed the minimum or maximum
Datevalue.Example: Halloween day of the week
As a kid, I always hoped for Halloween to fall on a weekend. With this program, we can print the day of the week for all Halloweens in the 2020s.
use ; let start = date; let mut halloween_days_of_week = vec!; for halloween in start.series.take assert_eq!;Example: how many times do I mow the lawn in a year?
I mow the lawn about every week and a half from the beginning of May to the end of October. About how many times will I mow the lawn in 2024?
use ; let start = date; let end = date; let mows = start .series .take_while .count; assert_eq!;Example: a period less than a day
Using a period less than a day works, but since this type exists at the granularity of a day, some dates may be repeated.
use ; let start = date; let every_five_hours: = start.series.take.collect; assert_eq!;Example: finding the most recent Friday the 13th
When did the most recent Friday the 13th occur?
use ; let start = date; let mut found = None; for date in start.series assert_eq!;
impl Date
fn strptime<impl AsRef<[u8]>: AsRef<[u8]>, impl AsRef<[u8]>: AsRef<[u8]>>(format: impl AsRef<[u8]>, input: impl AsRef<[u8]>) -> Result<Date, Error>Parses a civil date in
inputmatching the givenformat.The format string uses a "printf"-style API where conversion specifiers can be used as place holders to match components of a datetime. For details on the specifiers supported, see the
fmt::strtimemodule documentation.Errors
This returns an error when parsing failed. This might happen because the format string itself was invalid, or because the input didn't match the format string.
This also returns an error if there wasn't sufficient information to construct a civil date. For example, if an offset wasn't parsed.
Example
This example shows how to parse a civil date:
use Date; // Parse an American date with a two-digit year. let date = strptime?; assert_eq!; # Ok::fn strftime<'f, F: 'f + ?Sized + AsRef<[u8]>>(self: &Self, format: &'f F) -> Display<'f>Formats this civil date according to the given
format.The format string uses a "printf"-style API where conversion specifiers can be used as place holders to format components of a datetime. For details on the specifiers supported, see the
fmt::strtimemodule documentation.Errors and panics
While this routine itself does not error or panic, using the value returned may result in a panic if formatting fails. See the documentation on
fmt::strtime::Displayfor more information.To format in a way that surfaces errors without panicking, use either
fmt::strtime::formatorfmt::strtime::BrokenDownTime::format.Example
This example shows how to format a civil date:
use date; let date = date; let string = date.strftime.to_string; assert_eq!;
impl Add for Date
fn add(self: Self, rhs: Span) -> Date
impl Add for Date
fn add(self: Self, rhs: SignedDuration) -> Date
impl Add for Date
fn add(self: Self, rhs: UnsignedDuration) -> Date
impl AddAssign for Date
fn add_assign(self: &mut Self, rhs: SignedDuration)
impl AddAssign for Date
fn add_assign(self: &mut Self, rhs: UnsignedDuration)
impl AddAssign for Date
fn add_assign(self: &mut Self, rhs: Span)
impl Clone for Date
fn clone(self: &Self) -> Date
impl Copy for Date
impl Debug for Date
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Default for Date
fn default() -> Date
impl Display for Date
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Eq for Date
impl Freeze for Date
impl From for Date
fn from(weekdate: ISOWeekDate) -> Date
impl From for Date
fn from(dt: DateTime) -> Date
impl From for Date
fn from(zdt: Zoned) -> Date
impl FromStr for Date
fn from_str(string: &str) -> Result<Date, Error>
impl Hash for Date
fn hash<__H: $crate::hash::Hasher>(self: &Self, state: &mut __H)
impl Ord for Date
fn cmp(self: &Self, other: &Date) -> Ordering
impl PartialEq for Date
fn eq(self: &Self, other: &Date) -> bool
impl PartialOrd for Date
fn partial_cmp(self: &Self, other: &Date) -> Option<Ordering>
impl RefUnwindSafe for Date
impl Send for Date
impl Serialize for Date
fn serialize<S: serde::Serializer>(self: &Self, serializer: S) -> Result<<S as >::Ok, <S as >::Error>
impl Sub for Date
fn sub(self: Self, rhs: Span) -> Date
impl Sub for Date
fn sub(self: Self, rhs: SignedDuration) -> Date
impl Sub for Date
fn sub(self: Self, rhs: UnsignedDuration) -> Date
impl Sub for Date
fn sub(self: Self, rhs: Date) -> Span
impl SubAssign for Date
fn sub_assign(self: &mut Self, rhs: Span)
impl SubAssign for Date
fn sub_assign(self: &mut Self, rhs: SignedDuration)
impl SubAssign for Date
fn sub_assign(self: &mut Self, rhs: UnsignedDuration)
impl Sync for Date
impl Unpin for Date
impl UnsafeUnpin for Date
impl UnwindSafe for Date
impl<'a> From for Date
fn from(zdt: &'a Zoned) -> Date
impl<'de> Deserialize for Date
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Date, <D as >::Error>
impl<T> Any for Date
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Date
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Date
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for Date
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> DeserializeOwned for Date
impl<T> From for Date
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for Date
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T> ToString for Date
fn to_string(self: &Self) -> String
impl<T, U> Into for Date
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Date
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Date
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>