Skip to main content

pdf_forms/
datetime.rs

1use super::Object;
2
3#[cfg(feature = "chrono")]
4mod chrono_impl {
5    use crate::{Object, datetime::convert_utc_offset};
6    use chrono::prelude::*;
7
8    impl From<DateTime<Local>> for Object {
9        fn from(date: DateTime<Local>) -> Self {
10            let mut timezone_str = date.format("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
11            convert_utc_offset(&mut timezone_str);
12            Object::string_literal(timezone_str)
13        }
14    }
15
16    impl From<DateTime<Utc>> for Object {
17        fn from(date: DateTime<Utc>) -> Self {
18            Object::string_literal(date.format("D:%Y%m%d%H%M%SZ").to_string())
19        }
20    }
21
22    impl TryFrom<super::DateTime> for DateTime<Local> {
23        type Error = chrono::format::ParseError;
24
25        fn try_from(value: super::DateTime) -> Result<DateTime<Local>, Self::Error> {
26            let from_date = |date: NaiveDate| {
27                FixedOffset::east_opt(0)
28                    .unwrap()
29                    .from_utc_datetime(&date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap()))
30            };
31
32            DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S%#z")
33                .or_else(|_| DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%#z"))
34                .or_else(|_| NaiveDate::parse_from_str(&value.0, "%Y%m%d").map(from_date))
35                .map(|date| date.with_timezone(&Local))
36        }
37    }
38}
39
40#[cfg(feature = "jiff")]
41mod jiff_impl {
42    use crate::{Object, datetime::convert_utc_offset};
43    use jiff::{Timestamp, Zoned};
44
45    impl From<Zoned> for Object {
46        fn from(date: Zoned) -> Self {
47            let mut timezone_str = date.strftime("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
48            convert_utc_offset(&mut timezone_str);
49            Object::string_literal(timezone_str)
50        }
51    }
52
53    impl From<Timestamp> for Object {
54        fn from(date: Timestamp) -> Self {
55            Object::string_literal(date.strftime("D:%Y%m%d%H%M%SZ").to_string())
56        }
57    }
58
59    impl TryFrom<super::DateTime> for Zoned {
60        type Error = jiff::Error;
61
62        fn try_from(value: super::DateTime) -> Result<Self, Self::Error> {
63            use jiff::civil::{Date, DateTime};
64
65            // We attempt to parse different date time formats based on Section 7.9.4 "Dates" in
66            // PDF 32000-1:2008 here.
67            //
68            // "A PLUS SIGN as the value of the O field signifies that the local time is later than
69            // UT, a HYPHEN-MINUS signifies that local time is earlier than UT, and the LATIN
70            // CAPITAL Z signifies that local time is equal to UT. If no UT information is
71            // specified, the relationship of the specified time to UT shall be considered GMT."
72            //
73            // 1. Try parsing the full date and time with the `%#z` specifier to parse the timezone as a `Zoned` object.
74            // 2. Try parsing the full date and time with the 'Z' suffix as a `DateTime` interpreted to be in the UTC
75            //    timezone.
76            // 3. Try parsing the date and time without the seconds specified with the `%#z` specifier to parse the
77            //    timezone as a `Zoned` object.
78            // 4. Try parsing the date and time without the seconds specified with the 'Z' as a `DateTime` interpreted
79            //    to be in the UTC timezone.
80            // 5. Try parsing the date with no time as a `Date` interpreted to be in the GMT timezone.
81            //
82            // In all cases we return a `Zoned` object here to preserve the timezone.
83            Zoned::strptime("%Y%m%d%H%M%S%#z", &value.0)
84                .or_else(|_| {
85                    DateTime::strptime("%Y%m%d%H%M%SZ", &value.0).and_then(|dt| dt.in_tz("UTC"))
86                })
87                .or_else(|_| Zoned::strptime("%Y%m%d%H%M%#z", &value.0))
88                .or_else(|_| {
89                    DateTime::strptime("%Y%m%d%H%MZ", &value.0).and_then(|dt| dt.in_tz("UTC"))
90                })
91                .or_else(|_| {
92                    Date::strptime("%Y%m%d", &value.0).and_then(|dt| dt.at(0, 0, 0, 0).in_tz("GMT"))
93                })
94        }
95    }
96}
97
98#[cfg(feature = "time")]
99mod time_impl {
100    use crate::Object;
101    use time::{OffsetDateTime, Time, format_description::FormatItem};
102
103    impl From<Time> for Object {
104        fn from(date: Time) -> Self {
105            // can only fail if the TIME_FMT_ENCODE_STR would be invalid
106            Object::string_literal(
107                format!(
108                    "D:{}",
109                    date.format(&FormatItem::Literal("%Y%m%d%H%M%SZ".as_bytes()))
110                        .unwrap()
111                )
112                .into_bytes(),
113            )
114        }
115    }
116
117    impl From<OffsetDateTime> for Object {
118        fn from(date: OffsetDateTime) -> Self {
119            Object::string_literal({
120                // D:%Y%m%d%H%M%S:%z'
121                let format = time::format_description::parse(
122                    "D:[year][month][day][hour][minute][second][offset_hour sign:mandatory]'[offset_minute]'",
123                )
124                .unwrap();
125                date.format(&format).unwrap()
126            })
127        }
128    }
129
130    /// WARNING: `tm_wday` (weekday), `tm_yday` (day index in year), `tm_isdst`
131    /// (daylight saving time) and `tm_nsec` (nanoseconds of the date from 1970)
132    /// are set to 0 since they aren't available in the PDF time format. They could,
133    /// however, be calculated manually
134    impl TryFrom<super::DateTime> for OffsetDateTime {
135        type Error = time::Error;
136
137        fn try_from(value: super::DateTime) -> Result<OffsetDateTime, Self::Error> {
138            let format = time::format_description::parse(
139                "[year][month][day][hour][minute][second][offset_hour sign:mandatory][offset_minute]",
140            )
141            .unwrap();
142
143            Ok(OffsetDateTime::parse(&value.0, &format)?)
144        }
145    }
146}
147
148// Find the last `:` and turn it into an `'` to account for PDF weirdness
149#[allow(dead_code)]
150fn convert_utc_offset(bytes: &mut [u8]) {
151    let mut index = bytes.len();
152    while let Some(last) = bytes[..index].last_mut() {
153        if *last == b':' {
154            *last = b'\'';
155            break;
156        }
157        index -= 1;
158    }
159}
160
161#[derive(Clone, Debug)]
162pub struct DateTime(String);
163
164impl Object {
165    // Parses the `D`, `:` and `\` out of a `Object::String` to parse the date time
166    fn datetime_string(&self) -> Option<String> {
167        if let Object::String(bytes, _) = self {
168            String::from_utf8(
169                bytes
170                    .iter()
171                    .filter(|b| ![b'D', b':', b'\''].contains(b))
172                    .cloned()
173                    .collect(),
174            )
175            .ok()
176        } else {
177            None
178        }
179    }
180
181    pub fn as_datetime(&self) -> Option<DateTime> {
182        self.datetime_string().map(DateTime)
183    }
184}
185
186#[cfg(feature = "chrono")]
187#[test]
188fn parse_datetime_local() {
189    use chrono::prelude::*;
190
191    let time = Local::now().with_nanosecond(0).unwrap();
192    let text: Object = time.into();
193    let time2: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
194    assert_eq!(time2, Some(time));
195}
196
197#[cfg(feature = "chrono")]
198#[test]
199fn parse_datetime_utc() {
200    use chrono::prelude::*;
201
202    let time = Utc::now().with_nanosecond(0).unwrap();
203    let text: Object = time.into();
204    let time2: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
205    assert_eq!(time2, Some(time.with_timezone(&Local)));
206}
207
208#[cfg(feature = "jiff")]
209#[test]
210fn parse_zoned() {
211    use jiff::Zoned;
212
213    let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
214    let text: Object = time.clone().into();
215    let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
216    assert_eq!(time2, Some(time));
217}
218
219#[cfg(feature = "jiff")]
220#[test]
221fn parse_timestamp() {
222    use jiff::Zoned;
223
224    let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
225    let text: Object = time.timestamp().into();
226    let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
227    assert_eq!(time2, Some(time));
228}
229
230#[cfg(feature = "chrono")]
231#[test]
232fn parse_datetime_seconds_missing_chrono() {
233    use chrono::prelude::*;
234
235    // this is the example from the PDF reference, version 1.7, chapter 3.8.3
236    let text = Object::string_literal("D:199812231952-08'00'");
237    let dt: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
238    assert!(dt.is_some());
239}
240
241#[cfg(feature = "chrono")]
242#[test]
243fn parse_datetime_time_missing_chrono() {
244    use chrono::prelude::*;
245
246    let text = Object::string_literal("D:20040229");
247    let dt: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
248    assert!(dt.is_some());
249}
250
251#[cfg(feature = "jiff")]
252#[test]
253fn parse_datetime_seconds_missing_jiff() {
254    use jiff::Zoned;
255
256    // this is the example from the PDF reference, version 1.7, chapter 3.8.3
257    let text = Object::string_literal("D:199812231952-08'00'");
258    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
259    assert!(dt.is_some());
260}
261
262#[cfg(feature = "jiff")]
263#[test]
264fn parse_datetime_time_missing_jiff() {
265    use jiff::Zoned;
266
267    let text = Object::string_literal("D:20040229");
268    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
269    assert!(dt.is_some());
270}
271
272#[cfg(feature = "time")]
273#[test]
274fn parse_datetime() {
275    use time::OffsetDateTime;
276
277    let time = OffsetDateTime::now_utc();
278
279    let text: Object = time.into();
280    let time2: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
281
282    assert_eq!(time2.date(), time.date());
283
284    // Ignore nanoseconds
285    // - not important in the date parsing
286    assert_eq!(time2.time().hour(), time.time().hour());
287    assert_eq!(time2.time().minute(), time.time().minute());
288    assert_eq!(time2.time().second(), time.time().second());
289}