qubit_clock/clock/zoned_clock.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Clock trait with timezone support.
11//!
12//! This module defines the [`ZonedClock`] trait, which extends [`Clock`] to
13//! provide timezone support and local time access.
14//!
15
16use crate::Clock;
17use chrono::{
18 DateTime,
19 TimeZone,
20};
21use chrono_tz::Tz;
22
23/// A trait representing a clock with timezone support.
24///
25/// This trait extends [`Clock`] to provide timezone information and methods
26/// to get the current local time in the clock's timezone.
27///
28/// # Examples
29///
30/// ```
31/// use qubit_clock::{Clock, ZonedClock, SystemClock, Zoned};
32/// use chrono_tz::Asia::Shanghai;
33///
34/// let clock = Zoned::new(SystemClock::new(), Shanghai);
35/// let local = clock.local_time();
36/// println!("Local time in Shanghai: {}", local);
37/// ```
38///
39pub trait ZonedClock: Clock {
40 /// Returns the timezone of this clock.
41 ///
42 /// # Returns
43 ///
44 /// The timezone associated with this clock.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use qubit_clock::{ZonedClock, SystemClock, Zoned};
50 /// use chrono_tz::Asia::Shanghai;
51 ///
52 /// let clock = Zoned::new(SystemClock::new(), Shanghai);
53 /// assert_eq!(clock.timezone(), Shanghai);
54 /// ```
55 fn timezone(&self) -> Tz;
56
57 /// Returns the current local time in this clock's timezone.
58 ///
59 /// This method has a default implementation that converts the UTC time
60 /// from [`time()`](Clock::time) to the local time using the clock's
61 /// timezone.
62 ///
63 /// # Returns
64 ///
65 /// The current local time as a `DateTime<Tz>` object.
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// use qubit_clock::{ZonedClock, SystemClock, Zoned};
71 /// use chrono_tz::Asia::Shanghai;
72 ///
73 /// let clock = Zoned::new(SystemClock::new(), Shanghai);
74 /// let local = clock.local_time();
75 /// println!("Local time: {}", local);
76 /// ```
77 #[inline]
78 fn local_time(&self) -> DateTime<Tz> {
79 self.timezone().from_utc_datetime(&self.time().naive_utc())
80 }
81}