Skip to main content

vynil_core/
chrono.rs

1//! Date/time helper for Rhai.
2//!
3//! Provides `DateTimeHandler` (`date_now` + `format`) via `chrono_rhai_register`.
4
5use chrono::{DateTime, Local};
6#[cfg(feature = "rhai")] use rhai::{Engine, ImmutableString};
7
8/// Local date-time handle. Create with [`DateTimeHandler::now`] then [`DateTimeHandler::format`].
9#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
10pub struct DateTimeHandler {
11    pub date: DateTime<Local>,
12}
13impl DateTimeHandler {
14    #[must_use]
15    pub fn now() -> Self {
16        Self { date: Local::now() }
17    }
18
19    pub fn format(&self, fmt: &str) -> String {
20        format!("{}", self.date.format(fmt))
21    }
22
23    #[cfg(feature = "rhai")]
24    pub fn rhai_format(&mut self, fmt: String) -> ImmutableString {
25        self.format(&fmt).into()
26    }
27}
28
29#[cfg(feature = "rhai")]
30pub fn chrono_rhai_register(engine: &mut Engine) {
31    engine
32        .register_type_with_name::<DateTimeHandler>("DateTimeHandler")
33        .register_fn("date_now", DateTimeHandler::now)
34        .register_fn("format", DateTimeHandler::rhai_format);
35}