Skip to main content

typst_template/convert/
time.rs

1use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
2use typst::foundations::{Datetime, Value};
3
4use crate::ToValue;
5use crate::convert::datetime;
6
7// Dates outside Typst's range (years beyond ±9999) convert to `none`.
8fn ymd_hms(year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> Value {
9    datetime(year, month, day, hour, minute, second).map_or(Value::None, Value::Datetime)
10}
11
12impl ToValue for Date {
13    fn into_value(self) -> Value {
14        Datetime::from_ymd(self.year(), u8::from(self.month()), self.day()).map_or(Value::None, Value::Datetime)
15    }
16}
17
18impl ToValue for Time {
19    fn into_value(self) -> Value {
20        Datetime::from_hms(self.hour(), self.minute(), self.second()).map_or(Value::None, Value::Datetime)
21    }
22}
23
24impl ToValue for PrimitiveDateTime {
25    fn into_value(self) -> Value {
26        ymd_hms(self.year(), u8::from(self.month()), self.day(), self.hour(), self.minute(), self.second())
27    }
28}
29
30/// Uses the value's own UTC offset.
31impl ToValue for OffsetDateTime {
32    fn into_value(self) -> Value {
33        ymd_hms(self.year(), u8::from(self.month()), self.day(), self.hour(), self.minute(), self.second())
34    }
35}