1use 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#[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 #[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 #[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 #[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}