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