Skip to main content

android_chrono_tz/
local.rs

1// Copyright 2026 The android-chrono-tz Authors.
2// This project is dual-licensed under Apache 2.0 and MIT terms.
3// See LICENSE-APACHE and LICENSE-MIT for details.
4
5//! `Local` timezone type.
6
7use crate::{Tz, TzOffset, inner::TzInner};
8use chrono::{DateTime, MappedLocalTime, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
9use libc::time_t;
10use std::sync::Arc;
11
12/// The local system timezone as seen in Settings, from the `persist.sys.timezone` property.
13///
14/// Note that this ignores the `TZ` environment variable.
15#[derive(Copy, Clone, Debug)]
16pub struct Local;
17
18impl Local {
19    /// Returns a `DateTime<Local>` for the current date, time and timezone offset.
20    pub fn now() -> DateTime<Self> {
21        Utc::now().with_timezone(&Self)
22    }
23}
24
25impl TimeZone for Local {
26    type Offset = TzOffset;
27
28    fn from_offset(_offset: &TzOffset) -> Self {
29        Self
30    }
31
32    fn offset_from_local_date(&self, local: &NaiveDate) -> MappedLocalTime<TzOffset> {
33        self.offset_from_local_datetime(&local.and_time(NaiveTime::MIN))
34    }
35
36    fn offset_from_local_datetime(&self, local: &NaiveDateTime) -> MappedLocalTime<TzOffset> {
37        Tz::local().unwrap().offset_from_local_datetime(local)
38    }
39
40    fn offset_from_utc_date(&self, utc: &NaiveDate) -> TzOffset {
41        self.offset_from_utc_datetime(&utc.and_time(NaiveTime::MIN))
42    }
43
44    fn offset_from_utc_datetime(&self, utc: &NaiveDateTime) -> TzOffset {
45        TzOffset {
46            timezone: Arc::new(TzInner::local().unwrap()),
47            time: utc.and_utc().timestamp() as time_t,
48        }
49    }
50}