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 = "now",
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(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
18use rkyv::{Archive, Deserialize, Serialize};
19
20use super::{FixedOffset, MappedLocalTime, Offset, TimeZone};
21use crate::naive::{NaiveDate, NaiveDateTime};
22#[cfg(feature = "now")]
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::{DateTime, TimeZone, Utc};
37///
38/// let dt = DateTime::from_timestamp(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(
45    any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
46    derive(Archive, Deserialize, Serialize),
47    archive(compare(PartialEq)),
48    archive_attr(derive(Clone, Copy, PartialEq, Eq, Debug, Hash))
49)]
50#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
51#[cfg_attr(all(feature = "arbitrary", feature = "std"), derive(arbitrary::Arbitrary))]
52pub struct Utc;
53
54#[cfg(feature = "now")]
55impl Utc {
56    /// Returns a `Date` which corresponds to the current date.
57    #[deprecated(
58        since = "0.4.23",
59        note = "use `Utc::now()` instead, potentially with `.date_naive()`"
60    )]
61    #[allow(deprecated)]
62    #[must_use]
63    pub fn today() -> Date<Utc> {
64        Utc::now().date()
65    }
66
67    /// Returns a `DateTime<Utc>` which corresponds to the current date and time in UTC.
68    ///
69    /// See also the similar [`Local::now()`] which returns `DateTime<Local>`, i.e. the local date
70    /// and time including offset from UTC.
71    ///
72    /// [`Local::now()`]: crate::Local::now
73    ///
74    /// # Example
75    ///
76    /// ```
77    /// # #![allow(unused_variables)]
78    /// # use chrono::{FixedOffset, Utc};
79    /// // Current time in UTC
80    /// let now_utc = Utc::now();
81    ///
82    /// // Current date in UTC
83    /// let today_utc = now_utc.date_naive();
84    ///
85    /// // Current time in some timezone (let's use +05:00)
86    /// let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap();
87    /// let now_with_offset = Utc::now().with_timezone(&offset);
88    /// ```
89    #[cfg(not(all(
90        target_arch = "wasm32",
91        feature = "wasmbind",
92        not(any(target_os = "emscripten", target_os = "wasi"))
93    )))]
94    #[must_use]
95    pub fn now() -> DateTime<Utc> {
96        let now =
97            SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
98        DateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos()).unwrap()
99    }
100
101    /// Returns a `DateTime` which corresponds to the current date and time.
102    #[cfg(all(
103        target_arch = "wasm32",
104        feature = "wasmbind",
105        not(any(target_os = "emscripten", target_os = "wasi"))
106    ))]
107    #[must_use]
108    pub fn now() -> DateTime<Utc> {
109        let now = js_sys::Date::new_0();
110        DateTime::<Utc>::from(now)
111    }
112}
113
114impl TimeZone for Utc {
115    type Offset = Utc;
116
117    fn from_offset(_state: &Utc) -> Utc {
118        Utc
119    }
120
121    fn offset_from_local_date(&self, _local: &NaiveDate) -> MappedLocalTime<Utc> {
122        MappedLocalTime::Single(Utc)
123    }
124    fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> MappedLocalTime<Utc> {
125        MappedLocalTime::Single(Utc)
126    }
127
128    fn offset_from_utc_date(&self, _utc: &NaiveDate) -> Utc {
129        Utc
130    }
131    fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> Utc {
132        Utc
133    }
134}
135
136impl Offset for Utc {
137    fn fix(&self) -> FixedOffset {
138        FixedOffset::east_opt(0).unwrap()
139    }
140}
141
142impl fmt::Debug for Utc {
143    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144        write!(f, "Z")
145    }
146}
147
148impl fmt::Display for Utc {
149    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150        write!(f, "UTC")
151    }
152}