chrono/
date.rs

1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
3
4//! ISO 8601 calendar date with time zone.
5
6use core::borrow::Borrow;
7use core::{fmt, hash};
8use core::cmp::Ordering;
9use core::ops::{Add, Sub};
10use oldtime::Duration as OldDuration;
11
12use {Weekday, Datelike};
13use offset::{TimeZone, Utc};
14use naive::{self, NaiveDate, NaiveTime, IsoWeek};
15use DateTime;
16#[cfg(any(feature = "alloc", feature = "std", test))]
17use format::{DelayedFormat, Item, StrftimeItems};
18
19/// ISO 8601 calendar date with time zone.
20///
21/// This type should be considered ambiguous at best,
22/// due to the inherent lack of precision required for the time zone resolution.
23/// For serialization and deserialization uses, it is best to use `NaiveDate` instead.
24/// There are some guarantees on the usage of `Date<Tz>`:
25///
26/// - If properly constructed via `TimeZone::ymd` and others without an error,
27///   the corresponding local date should exist for at least a moment.
28///   (It may still have a gap from the offset changes.)
29///
30/// - The `TimeZone` is free to assign *any* `Offset` to the local date,
31///   as long as that offset did occur in given day.
32///   For example, if `2015-03-08T01:59-08:00` is followed by `2015-03-08T03:00-07:00`,
33///   it may produce either `2015-03-08-08:00` or `2015-03-08-07:00`
34///   but *not* `2015-03-08+00:00` and others.
35///
36/// - Once constructed as a full `DateTime`,
37///   `DateTime::date` and other associated methods should return those for the original `Date`.
38///   For example, if `dt = tz.ymd(y,m,d).hms(h,n,s)` were valid, `dt.date() == tz.ymd(y,m,d)`.
39///
40/// - The date is timezone-agnostic up to one day (i.e. practically always),
41///   so the local date and UTC date should be equal for most cases
42///   even though the raw calculation between `NaiveDate` and `Duration` may not.
43#[derive(Clone)]
44pub struct Date<Tz: TimeZone> {
45    date: NaiveDate,
46    offset: Tz::Offset,
47}
48
49/// The minimum possible `Date`.
50pub const MIN_DATE: Date<Utc> = Date { date: naive::MIN_DATE, offset: Utc };
51/// The maximum possible `Date`.
52pub const MAX_DATE: Date<Utc> = Date { date: naive::MAX_DATE, offset: Utc };
53
54impl<Tz: TimeZone> Date<Tz> {
55    /// Makes a new `Date` with given *UTC* date and offset.
56    /// The local date should be constructed via the `TimeZone` trait.
57    //
58    // note: this constructor is purposedly not named to `new` to discourage the direct usage.
59    #[inline]
60    pub fn from_utc(date: NaiveDate, offset: Tz::Offset) -> Date<Tz> {
61        Date { date: date, offset: offset }
62    }
63
64    /// Makes a new `DateTime` from the current date and given `NaiveTime`.
65    /// The offset in the current date is preserved.
66    ///
67    /// Panics on invalid datetime.
68    #[inline]
69    pub fn and_time(&self, time: NaiveTime) -> Option<DateTime<Tz>> {
70        let localdt = self.naive_local().and_time(time);
71        self.timezone().from_local_datetime(&localdt).single()
72    }
73
74    /// Makes a new `DateTime` from the current date, hour, minute and second.
75    /// The offset in the current date is preserved.
76    ///
77    /// Panics on invalid hour, minute and/or second.
78    #[inline]
79    pub fn and_hms(&self, hour: u32, min: u32, sec: u32) -> DateTime<Tz> {
80        self.and_hms_opt(hour, min, sec).expect("invalid time")
81    }
82
83    /// Makes a new `DateTime` from the current date, hour, minute and second.
84    /// The offset in the current date is preserved.
85    ///
86    /// Returns `None` on invalid hour, minute and/or second.
87    #[inline]
88    pub fn and_hms_opt(&self, hour: u32, min: u32, sec: u32) -> Option<DateTime<Tz>> {
89        NaiveTime::from_hms_opt(hour, min, sec).and_then(|time| self.and_time(time))
90    }
91
92    /// Makes a new `DateTime` from the current date, hour, minute, second and millisecond.
93    /// The millisecond part can exceed 1,000 in order to represent the leap second.
94    /// The offset in the current date is preserved.
95    ///
96    /// Panics on invalid hour, minute, second and/or millisecond.
97    #[inline]
98    pub fn and_hms_milli(&self, hour: u32, min: u32, sec: u32, milli: u32) -> DateTime<Tz> {
99        self.and_hms_milli_opt(hour, min, sec, milli).expect("invalid time")
100    }
101
102    /// Makes a new `DateTime` from the current date, hour, minute, second and millisecond.
103    /// The millisecond part can exceed 1,000 in order to represent the leap second.
104    /// The offset in the current date is preserved.
105    ///
106    /// Returns `None` on invalid hour, minute, second and/or millisecond.
107    #[inline]
108    pub fn and_hms_milli_opt(&self, hour: u32, min: u32, sec: u32,
109                             milli: u32) -> Option<DateTime<Tz>> {
110        NaiveTime::from_hms_milli_opt(hour, min, sec, milli).and_then(|time| self.and_time(time))
111    }
112
113    /// Makes a new `DateTime` from the current date, hour, minute, second and microsecond.
114    /// The microsecond part can exceed 1,000,000 in order to represent the leap second.
115    /// The offset in the current date is preserved.
116    ///
117    /// Panics on invalid hour, minute, second and/or microsecond.
118    #[inline]
119    pub fn and_hms_micro(&self, hour: u32, min: u32, sec: u32, micro: u32) -> DateTime<Tz> {
120        self.and_hms_micro_opt(hour, min, sec, micro).expect("invalid time")
121    }
122
123    /// Makes a new `DateTime` from the current date, hour, minute, second and microsecond.
124    /// The microsecond part can exceed 1,000,000 in order to represent the leap second.
125    /// The offset in the current date is preserved.
126    ///
127    /// Returns `None` on invalid hour, minute, second and/or microsecond.
128    #[inline]
129    pub fn and_hms_micro_opt(&self, hour: u32, min: u32, sec: u32,
130                             micro: u32) -> Option<DateTime<Tz>> {
131        NaiveTime::from_hms_micro_opt(hour, min, sec, micro).and_then(|time| self.and_time(time))
132    }
133
134    /// Makes a new `DateTime` from the current date, hour, minute, second and nanosecond.
135    /// The nanosecond part can exceed 1,000,000,000 in order to represent the leap second.
136    /// The offset in the current date is preserved.
137    ///
138    /// Panics on invalid hour, minute, second and/or nanosecond.
139    #[inline]
140    pub fn and_hms_nano(&self, hour: u32, min: u32, sec: u32, nano: u32) -> DateTime<Tz> {
141        self.and_hms_nano_opt(hour, min, sec, nano).expect("invalid time")
142    }
143
144    /// Makes a new `DateTime` from the current date, hour, minute, second and nanosecond.
145    /// The nanosecond part can exceed 1,000,000,000 in order to represent the leap second.
146    /// The offset in the current date is preserved.
147    ///
148    /// Returns `None` on invalid hour, minute, second and/or nanosecond.
149    #[inline]
150    pub fn and_hms_nano_opt(&self, hour: u32, min: u32, sec: u32,
151                            nano: u32) -> Option<DateTime<Tz>> {
152        NaiveTime::from_hms_nano_opt(hour, min, sec, nano).and_then(|time| self.and_time(time))
153    }
154
155    /// Makes a new `Date` for the next date.
156    ///
157    /// Panics when `self` is the last representable date.
158    #[inline]
159    pub fn succ(&self) -> Date<Tz> {
160        self.succ_opt().expect("out of bound")
161    }
162
163    /// Makes a new `Date` for the next date.
164    ///
165    /// Returns `None` when `self` is the last representable date.
166    #[inline]
167    pub fn succ_opt(&self) -> Option<Date<Tz>> {
168        self.date.succ_opt().map(|date| Date::from_utc(date, self.offset.clone()))
169    }
170
171    /// Makes a new `Date` for the prior date.
172    ///
173    /// Panics when `self` is the first representable date.
174    #[inline]
175    pub fn pred(&self) -> Date<Tz> {
176        self.pred_opt().expect("out of bound")
177    }
178
179    /// Makes a new `Date` for the prior date.
180    ///
181    /// Returns `None` when `self` is the first representable date.
182    #[inline]
183    pub fn pred_opt(&self) -> Option<Date<Tz>> {
184        self.date.pred_opt().map(|date| Date::from_utc(date, self.offset.clone()))
185    }
186
187    /// Retrieves an associated offset from UTC.
188    #[inline]
189    pub fn offset(&self) -> &Tz::Offset {
190        &self.offset
191    }
192
193    /// Retrieves an associated time zone.
194    #[inline]
195    pub fn timezone(&self) -> Tz {
196        TimeZone::from_offset(&self.offset)
197    }
198
199    /// Changes the associated time zone.
200    /// This does not change the actual `Date` (but will change the string representation).
201    #[inline]
202    pub fn with_timezone<Tz2: TimeZone>(&self, tz: &Tz2) -> Date<Tz2> {
203        tz.from_utc_date(&self.date)
204    }
205
206    /// Adds given `Duration` to the current date.
207    ///
208    /// Returns `None` when it will result in overflow.
209    #[inline]
210    pub fn checked_add_signed(self, rhs: OldDuration) -> Option<Date<Tz>> {
211        let date = try_opt!(self.date.checked_add_signed(rhs));
212        Some(Date { date: date, offset: self.offset })
213    }
214
215    /// Subtracts given `Duration` from the current date.
216    ///
217    /// Returns `None` when it will result in overflow.
218    #[inline]
219    pub fn checked_sub_signed(self, rhs: OldDuration) -> Option<Date<Tz>> {
220        let date = try_opt!(self.date.checked_sub_signed(rhs));
221        Some(Date { date: date, offset: self.offset })
222    }
223
224    /// Subtracts another `Date` from the current date.
225    /// Returns a `Duration` of integral numbers.
226    ///
227    /// This does not overflow or underflow at all,
228    /// as all possible output fits in the range of `Duration`.
229    #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
230    #[inline]
231    pub fn signed_duration_since<Tz2: TimeZone>(self, rhs: Date<Tz2>) -> OldDuration {
232        self.date.signed_duration_since(rhs.date)
233    }
234
235    /// Returns a view to the naive UTC date.
236    #[inline]
237    pub fn naive_utc(&self) -> NaiveDate {
238        self.date
239    }
240
241    /// Returns a view to the naive local date.
242    ///
243    /// This is technically same to [`naive_utc`](#method.naive_utc)
244    /// because the offset is restricted to never exceed one day,
245    /// but provided for the consistency.
246    #[inline]
247    pub fn naive_local(&self) -> NaiveDate {
248        self.date
249    }
250}
251
252/// Maps the local date to other date with given conversion function.
253fn map_local<Tz: TimeZone, F>(d: &Date<Tz>, mut f: F) -> Option<Date<Tz>>
254        where F: FnMut(NaiveDate) -> Option<NaiveDate> {
255    f(d.naive_local()).and_then(|date| d.timezone().from_local_date(&date).single())
256}
257
258impl<Tz: TimeZone> Date<Tz> where Tz::Offset: fmt::Display {
259    /// Formats the date with the specified formatting items.
260    #[cfg(any(feature = "alloc", feature = "std", test))]
261    #[inline]
262    pub fn format_with_items<'a, I, B>(&self, items: I) -> DelayedFormat<I>
263            where I: Iterator<Item=B> + Clone, B: Borrow<Item<'a>> {
264        DelayedFormat::new_with_offset(Some(self.naive_local()), None, &self.offset, items)
265    }
266
267    /// Formats the date with the specified format string.
268    /// See the [`format::strftime` module](./format/strftime/index.html)
269    /// on the supported escape sequences.
270    #[cfg(any(feature = "alloc", feature = "std", test))]
271    #[inline]
272    pub fn format<'a>(&self, fmt: &'a str) -> DelayedFormat<StrftimeItems<'a>> {
273        self.format_with_items(StrftimeItems::new(fmt))
274    }
275}
276
277impl<Tz: TimeZone> Datelike for Date<Tz> {
278    #[inline] fn year(&self) -> i32 { self.naive_local().year() }
279    #[inline] fn month(&self) -> u32 { self.naive_local().month() }
280    #[inline] fn month0(&self) -> u32 { self.naive_local().month0() }
281    #[inline] fn day(&self) -> u32 { self.naive_local().day() }
282    #[inline] fn day0(&self) -> u32 { self.naive_local().day0() }
283    #[inline] fn ordinal(&self) -> u32 { self.naive_local().ordinal() }
284    #[inline] fn ordinal0(&self) -> u32 { self.naive_local().ordinal0() }
285    #[inline] fn weekday(&self) -> Weekday { self.naive_local().weekday() }
286    #[inline] fn iso_week(&self) -> IsoWeek { self.naive_local().iso_week() }
287
288    #[inline]
289    fn with_year(&self, year: i32) -> Option<Date<Tz>> {
290        map_local(self, |date| date.with_year(year))
291    }
292
293    #[inline]
294    fn with_month(&self, month: u32) -> Option<Date<Tz>> {
295        map_local(self, |date| date.with_month(month))
296    }
297
298    #[inline]
299    fn with_month0(&self, month0: u32) -> Option<Date<Tz>> {
300        map_local(self, |date| date.with_month0(month0))
301    }
302
303    #[inline]
304    fn with_day(&self, day: u32) -> Option<Date<Tz>> {
305        map_local(self, |date| date.with_day(day))
306    }
307
308    #[inline]
309    fn with_day0(&self, day0: u32) -> Option<Date<Tz>> {
310        map_local(self, |date| date.with_day0(day0))
311    }
312
313    #[inline]
314    fn with_ordinal(&self, ordinal: u32) -> Option<Date<Tz>> {
315        map_local(self, |date| date.with_ordinal(ordinal))
316    }
317
318    #[inline]
319    fn with_ordinal0(&self, ordinal0: u32) -> Option<Date<Tz>> {
320        map_local(self, |date| date.with_ordinal0(ordinal0))
321    }
322}
323
324// we need them as automatic impls cannot handle associated types
325impl<Tz: TimeZone> Copy for Date<Tz> where <Tz as TimeZone>::Offset: Copy {}
326unsafe impl<Tz: TimeZone> Send for Date<Tz> where <Tz as TimeZone>::Offset: Send {}
327
328impl<Tz: TimeZone, Tz2: TimeZone> PartialEq<Date<Tz2>> for Date<Tz> {
329    fn eq(&self, other: &Date<Tz2>) -> bool { self.date == other.date }
330}
331
332impl<Tz: TimeZone> Eq for Date<Tz> {
333}
334
335impl<Tz: TimeZone> PartialOrd for Date<Tz> {
336    fn partial_cmp(&self, other: &Date<Tz>) -> Option<Ordering> {
337        self.date.partial_cmp(&other.date)
338    }
339}
340
341impl<Tz: TimeZone> Ord for Date<Tz> {
342    fn cmp(&self, other: &Date<Tz>) -> Ordering { self.date.cmp(&other.date) }
343}
344
345impl<Tz: TimeZone> hash::Hash for Date<Tz> {
346    fn hash<H: hash::Hasher>(&self, state: &mut H) { self.date.hash(state) }
347}
348
349impl<Tz: TimeZone> Add<OldDuration> for Date<Tz> {
350    type Output = Date<Tz>;
351
352    #[inline]
353    fn add(self, rhs: OldDuration) -> Date<Tz> {
354        self.checked_add_signed(rhs).expect("`Date + Duration` overflowed")
355    }
356}
357
358impl<Tz: TimeZone> Sub<OldDuration> for Date<Tz> {
359    type Output = Date<Tz>;
360
361    #[inline]
362    fn sub(self, rhs: OldDuration) -> Date<Tz> {
363        self.checked_sub_signed(rhs).expect("`Date - Duration` overflowed")
364    }
365}
366
367impl<Tz: TimeZone> Sub<Date<Tz>> for Date<Tz> {
368    type Output = OldDuration;
369
370    #[inline]
371    fn sub(self, rhs: Date<Tz>) -> OldDuration {
372        self.signed_duration_since(rhs)
373    }
374}
375
376impl<Tz: TimeZone> fmt::Debug for Date<Tz> {
377    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378        write!(f, "{:?}{:?}", self.naive_local(), self.offset)
379    }
380}
381
382impl<Tz: TimeZone> fmt::Display for Date<Tz> where Tz::Offset: fmt::Display {
383    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
384        write!(f, "{}{}", self.naive_local(), self.offset)
385    }
386}
387