1// This is a part of Chrono.
2// See README.md and LICENSE.txt for details.
34//! The UTC (Coordinated Universal Time) time zone.
56use 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};
1617#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
18use rkyv::{Archive, Deserialize, Serialize};
1920use super::{FixedOffset, LocalResult, Offset, TimeZone};
21use crate::naive::{NaiveDate, NaiveDateTime};
22#[cfg(feature = "now")]
23#[allow(deprecated)]
24use crate::{Date, DateTime};
2526/// 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(
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;
5354#[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]
63pub fn today() -> Date<Utc> {
64 Utc::now().date()
65 }
6667/// 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]
95pub fn now() -> DateTime<Utc> {
96let now =
97 SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
98let naive =
99 NaiveDateTime::from_timestamp_opt(now.as_secs() as i64, now.subsec_nanos()).unwrap();
100 Utc.from_utc_datetime(&naive)
101 }
102103/// Returns a `DateTime` which corresponds to the current date and time.
104#[cfg(all(
105 target_arch = "wasm32",
106 feature = "wasmbind",
107 not(any(target_os = "emscripten", target_os = "wasi"))
108 ))]
109 #[must_use]
110pub fn now() -> DateTime<Utc> {
111let now = js_sys::Date::new_0();
112 DateTime::<Utc>::from(now)
113 }
114}
115116impl TimeZone for Utc {
117type Offset = Utc;
118119fn from_offset(_state: &Utc) -> Utc {
120 Utc
121 }
122123fn offset_from_local_date(&self, _local: &NaiveDate) -> LocalResult<Utc> {
124 LocalResult::Single(Utc)
125 }
126fn offset_from_local_datetime(&self, _local: &NaiveDateTime) -> LocalResult<Utc> {
127 LocalResult::Single(Utc)
128 }
129130fn offset_from_utc_date(&self, _utc: &NaiveDate) -> Utc {
131 Utc
132 }
133fn offset_from_utc_datetime(&self, _utc: &NaiveDateTime) -> Utc {
134 Utc
135 }
136}
137138impl Offset for Utc {
139fn fix(&self) -> FixedOffset {
140 FixedOffset::east_opt(0).unwrap()
141 }
142}
143144impl fmt::Debug for Utc {
145fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146write!(f, "Z")
147 }
148}
149150impl fmt::Display for Utc {
151fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152write!(f, "UTC")
153 }
154}