Skip to content

Commit

Permalink
Parse PDF datetime value
Browse files Browse the repository at this point in the history
  • Loading branch information
J-F-Liu committed Mar 7, 2017
1 parent 00113c0 commit a04ad03
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
19 changes: 19 additions & 0 deletions benches/datetime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#![feature(test)]
extern crate test;
use test::Bencher;

extern crate lopdf;
use lopdf::Object;

extern crate chrono;
use chrono::prelude::{Local, Timelike};

#[bench]
fn create_and_parse_datetime(b: &mut Bencher) {
b.iter(|| {
let time = Local::now().with_nanosecond(0).unwrap();
let text: Object = time.into();
let time2 = text.as_datetime();
assert_eq!(time2, Some(time));
});
}
35 changes: 32 additions & 3 deletions src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ use super::{Object, StringFormat};

impl From<DateTime<Local>> for Object {
fn from(date: DateTime<Local>) -> Self {
let mut text = date.format("%Y%m%d%H%M%S%:z'").to_string().replace(':', "'");
text.insert_str(0, "D:");
Object::String(text.into_bytes(), StringFormat::Literal)
let mut bytes = date.format("D:%Y%m%d%H%M%S%:z'").to_string().into_bytes();
let mut index = bytes.len();
while let Some(last) = bytes[..index].last_mut() {
if *last == b':' {
*last = b'\'';
break;
}
index -= 1;
}
Object::String(bytes, StringFormat::Literal)
}
}

Expand All @@ -14,3 +21,25 @@ impl From<DateTime<UTC>> for Object {
Object::String(date.format("D:%Y%m%d%H%M%SZ").to_string().into_bytes(), StringFormat::Literal)
}
}

impl Object {
pub fn as_datetime(&self) -> Option<DateTime<Local>> {
match *self {
Object::String(ref bytes, _) => {
let text = String::from_utf8(
bytes.iter().filter(|b| ![b'D', b':', b'\''].contains(b)).map(|b|*b).collect()
).unwrap();
Local.datetime_from_str(&text, "%Y%m%d%H%M%S%z").ok()
},
_ => None
}
}
}

#[test]
fn parse_datetime() {
let time = Local::now().with_nanosecond(0).unwrap();
let text: Object = time.into();
let time2 = text.as_datetime();
assert_eq!(time2, Some(time));
}

0 comments on commit a04ad03

Please sign in to comment.