chrono/offset/
utc.rs

1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
3
4//! The UTC (Coordinated Universal Time) time zone.
5
6use core::fmt;
7#[cfg(all(
8    feature = "clock",
9    not(all(
10        target_arch = "wasm32",
11        feature = "wasmbind",
12        not(any(target_os = "emscripten", target_os = "wasi"))
13    ))
14))]
15use std::time::{SystemTime, UNIX_EPOCH};
16
17#[cfg(feature = "rkyv")]
18use rkyv::{Archive, Deserialize, Serialize};
19
20use super::{FixedOffset, LocalResult, Offset, TimeZone};
21use crate::naive::{NaiveDate, NaiveDateTime};
22#[cfg(feature = "clock")]
23#[allow(deprecated)]
24use crate::{Date, DateTime};
25
26/// The UTC time zone. This is the most efficient time zone when you don't need the local time.
27/// It is also used as an offset (which is also a dummy type).
28///
29/// Using the [`TimeZone`](./trait.TimeZone.html) methods
30/// on the UTC struct is the preferred way to construct `DateTime<Utc>`
31/// instances.
32///
33/// # Example
34///
35/// ```
36/// use chrono::{TimeZone, NaiveDateTime, Utc};
37///
38/// let dt = Utc.from_utc_datetime(&NaiveDateTime::from_timestamp_opt(61, 0).unwrap());
39///
40/// assert_eq!(Utc.timestamp_opt(61, 0).unwrap(), dt);
41/// assert_eq!(Utc.with_ymd_and_hms(1970, 1, 1, 0, 1, 1).unwrap(), dt);
42/// ```
43#[derive(Copy, Clone, PartialEq, Eq, Hash)]
44#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
45#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
46pub struct Utc;
47
48#[cfg(feature = "clock")]
49#[cfg_attr(docsrs, doc(cfg(feature = "clock")))]
50impl Utc {
51    /// Returns a `Date` which corresponds to the current date.
52    #[deprecated(
53        since = "0.4.23",
54        note = "use `Utc::now()` instead, potentially with `.date_naive()`"
55    )]
56    #[allow(deprecated)]
57    #[must_use]
58    pub fn today() -> Date<Utc> {
59        Utc::now().date()
60    }
61
62    /// Returns a `DateTime<Utc>` which corresponds to the current date and time in UTC.
63    ///
64    /// See also the similar [`Local::now()`] which returns `DateTime<Local>`, i.e. the local date
65    /// and time including offset from UTC.
66    ///
67    /// [`Local::now()`]: crate::Local::now
68    ///
69    /// # Example
70    ///
71    /// ```
72    /// # #![allow(unused_variables)]
73    /// # use chrono::{FixedOffset, Utc};
74    /// // Current time in UTC
75    /// let now_utc = Utc::now();
76    ///
77    /// // Current date in UTC
78    /// let today_utc = now_utc.date_naive();
79    ///
80    /// // Current time in some timezone (let's use +05:00)
81    /// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap();
82    /// let now_with_offset = Utc::now().with_timezone(&offset);
83    /// ```
84    #[cfg(not(all(
85        target_arch = "wasm32",
86        feature = "wasmbind",
87        not(any(target_os = "emscripten", target_os = "wasi"))
88    )))]
89    #[must_use]
90    pub fn now() -> DateTime<Utc> {
91        let now =
92            SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
93        let naive =
94            NaiveDateTime::from_timestamp_opt(now.as_secs() as i64, now.subsec_nanos()).unwrap();
95        Utc.from_utc_datetime(&naive)
96    }
97
98    /// Returns a `DateTime` which corresponds to the current date and time.
99    #[cfg(all(
100        target_arch = "wasm32",
101        feature = "wasmbind",
102        not(any(target_os = "emscripten", target_os = "wasi"))
103    ))]
104    #[must_use]
105    pub fn now() -> DateTime<Utc> {
106        let now = js_sys::Date::new_0();
107        DateTime::<Utc>::from(now)
108    }
109}
110
111impl TimeZone for Utc {
112    type Offset = Utc;
113
114    fn from_offset(_state: &Utc) -> Utc {
115        Utc
116    }
117
118    fn offset_from_local_date(&self, _local: &NaiveDate) -> LocalResult<Utc> {
119        LocalResult::Single(Utc)
120    }
121    fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> LocalResult<Utc> {
122        LocalResult::Single(Utc)
123    }
124
125    fn offset_from_utc_date(&self, _utc: &NaiveDate) -> Utc {
126        Utc
127    }
128    fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> Utc {
129        Utc
130    }
131}
132
133impl Offset for Utc {
134    fn fix(&self) -> FixedOffset {
135        FixedOffset::east_opt(0).unwrap()
136    }
137}
138
139impl fmt::Debug for Utc {
140    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141        write!(f, "Z")
142    }
143}
144
145impl fmt::Display for Utc {
146    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
147        write!(f, "UTC")
148    }
149}