add try_from/try_into

This commit is contained in:
2020-06-25 13:44:51 +08:00
parent 8f5d3666f2
commit 626a46ff7c
2 changed files with 19 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
#[macro_use] extern crate quick_error; #[macro_use] extern crate quick_error;
use chrono::prelude::*; use chrono::prelude::*;
use std::{ use std::{
convert::TryFrom,
time::Duration, time::Duration,
str::Chars, str::Chars,
iter::Peekable, iter::Peekable,
@@ -181,6 +182,14 @@ pub fn fmt(f: &str) -> Result<SimpleDateFormat, ParseError> {
Ok(SimpleDateFormat{ parts }) Ok(SimpleDateFormat{ parts })
} }
impl TryFrom<&str> for SimpleDateFormat {
type Error = ParseError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
SimpleDateFormat::new(s)
}
}
fn format_zone<Tz>(date_time: &DateTime<Tz>, _cnt: usize) -> String where Tz: TimeZone { fn format_zone<Tz>(date_time: &DateTime<Tz>, _cnt: usize) -> String where Tz: TimeZone {
format!("{:?}", date_time.offset()) format!("{:?}", date_time.offset())
} }

View File

@@ -1,4 +1,4 @@
use simpledateformat::{ fmt, format_human, }; use simpledateformat::{ SimpleDateFormat, fmt, format_human, };
use chrono::prelude::*; use chrono::prelude::*;
use std::time::Duration; use std::time::Duration;
@@ -35,3 +35,12 @@ fn test_format_human() {
assert_eq!("2days", format_human(Duration::from_secs(2 * 24 * 60 * 60))); assert_eq!("2days", format_human(Duration::from_secs(2 * 24 * 60 * 60)));
assert_eq!("2days 0hour 0min 1s", format_human(Duration::from_secs(2 * 24 * 60 * 60 + 1))); assert_eq!("2days 0hour 0min 1s", format_human(Duration::from_secs(2 * 24 * 60 * 60 + 1)));
} }
#[test]
fn test_try_from() {
use std::convert::TryInto;
let t = Utc.timestamp_millis(0);
let fmt = "yyyy/MM/dd HH:mm:ss.SSS z";
let sdf: Result<SimpleDateFormat, _> = fmt.try_into();
assert_eq!("1970/01/01 00:00:00.000 Z", sdf.unwrap().format(&t));
}