1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! A rust library for parsing date/time strings from various formats
//! and normalising to a standard fixed offset format (rfc3339).
//! Parsed date will be returned `DateTime<FixedOffset>`
//!

use chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, ParseError, TimeZone, Datelike};

#[cfg(test)]
mod tests;

type Error = String;

/// DateTimeFixedOffset returns a str containing date time to a
/// standard datetime fixed offset RFC 3339 format.
///
/// ## Example usage:
/// ```
/// use datetime_parse::DateTimeFixedOffset;
///
/// let date_str = "Mon, 6 Jul 1970 15:30:00 PDT";
/// let result = date_str.parse::<DateTimeFixedOffset>();
/// assert!(result.is_ok());
/// match result {
///     Ok(parsed) => println!("{} => {:?}", date_str, parsed.0),
///     Err(e) => println!("Error: {}", e)
/// }
/// ```
#[derive(Debug)]
pub struct DateTimeFixedOffset(pub DateTime<FixedOffset>);

impl std::str::FromStr for DateTimeFixedOffset {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Error> {
        parse_from(s).map(DateTimeFixedOffset)
    }
}

/// parse_from interprets the input date/time slice and returns a normalised parsed date/time
/// as DateTime<FixedOffset> or will return an Error
fn parse_from(date_time: &str) -> Result<DateTime<FixedOffset>, Error> {
    let date_time = standardize_date(date_time);
    DateTime::parse_from_str(&date_time, "%+")
        .or_else(|_| from_datetime_with_tz(&date_time))
        .or_else(|_| from_datetime_without_tz(&date_time))
        .or_else(|_| from_date_without_tz(&date_time))
        .or_else(|_| from_time_without_tz(&date_time))
        .or_else(|_| try_yms_hms_tz(&date_time))
        .or_else(|_| try_syslog_format(&date_time))
}

/// Convert a `datetime` string to `DateTime<FixedOffset>`
fn from_datetime_with_tz(s: &str) -> Result<DateTime<FixedOffset>, ParseError> {
    DateTime::parse_from_rfc3339(s)
        .or_else(|_| DateTime::parse_from_rfc2822(s))
        .or_else(|_| DateTime::parse_from_str(s, "%Y-%m-%dT%T%.f%z"))
        .or_else(|_| DateTime::parse_from_str(s, "%Y-%m-%d %T%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%Y-%m-%d %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B %d, %Y; %T %#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B %d, %Y; %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B %d %Y %T %#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B %d %Y %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B, %d %Y %T %#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%B, %d %Y %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%A, %d %B %Y %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%A %d %B %Y %T.%f%#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%A, %d %B %Y %T %#z"))
        .or_else(|_| DateTime::parse_from_str(s, "%A %d %B %Y %T %#z"))
}

/// Convert a `datetime` string, that which mostly does not have a timezone info
/// to Datetime fixed offset with local timezone
fn from_datetime_without_tz(s: &str) -> Result<DateTime<FixedOffset>, ParseError> {
    Local
        .datetime_from_str(s, "%Y-%m-%dT%T")
        .or_else(|_| Local.datetime_from_str(s, "%Y-%m-%dT%T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%Y-%m-%d %T"))
        .or_else(|_| Local.datetime_from_str(s, "%Y-%m-%d %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%B %d %Y %T"))
        .or_else(|_| Local.datetime_from_str(s, "%B %d %Y %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%B %d, %Y %T"))
        .or_else(|_| Local.datetime_from_str(s, "%B %d, %Y %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%Y-%m-%d %T"))
        .or_else(|_| Local.datetime_from_str(s, "%Y-%m-%d %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%A, %d %B %Y %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%A %d %B %Y %T.%f"))
        .or_else(|_| Local.datetime_from_str(s, "%A, %d %B %Y %T"))
        .or_else(|_| Local.datetime_from_str(s, "%A %d %B %Y %T"))
        .map(|x| x.with_timezone(x.offset()))
}

/// Convert just `date` string without time or timezone information
/// to Datetime fixed offset with local timezone
fn from_date_without_tz(s: &str) -> Result<DateTime<FixedOffset>, Error> {
    NaiveDate::parse_from_str(s, "%Y-%m-%d")
        .or_else(|_| NaiveDate::parse_from_str(s, "%m-%d-%y"))
        .or_else(|_| NaiveDate::parse_from_str(s, "%D"))
        .or_else(|_| NaiveDate::parse_from_str(s, "%F"))
        .or_else(|_| NaiveDate::parse_from_str(s, "%v"))
        .or_else(|_| NaiveDate::parse_from_str(s, "%B %d %Y"))
        .map(|x| x.and_hms(0, 0, 0))
        .map(|x| Local.from_local_datetime(&x))
        .map_err(|e| e.to_string())
        .map(|x| x.unwrap().with_timezone(x.unwrap().offset()))
}

/// Convert just `time` string without date or timezone information
/// to Datetime fixed offset with local timezone & current date
fn from_time_without_tz(s: &str) -> Result<DateTime<FixedOffset>, ParseError> {
    NaiveTime::parse_from_str(s, "%T")
        .or_else(|_| NaiveTime::parse_from_str(s, "%I:%M%P"))
        .or_else(|_| NaiveTime::parse_from_str(s, "%I:%M %P"))
        .map(|x| Local::now().date().and_time(x).unwrap().naive_local())
        .map(|x| DateTime::from_utc(x, FixedOffset::east(0)))
}

/// Try to parse the following types of dates
/// 1970-12-25 16:16:16 PST
/// 1970-12-25 16:16 PST
fn try_yms_hms_tz(s: &str) -> Result<DateTime<FixedOffset>, Error> {
    if let Some((dt, tz)) = is_tz_alpha(s) {
        to_rfc2822(dt, &tz)
    } else {
        Err("yms_hms_tz failed".to_string())
    }
}

/// Try to parse the following types of dates (partially syslog format)
/// Feb 12 12:12:12
/// Feb 12
fn try_syslog_format(s: &str) -> Result<DateTime<FixedOffset>, Error> {
    let date = s.split_whitespace().collect::<Vec<_>>();
    let year = Local::now().year();
    if date.len().eq(&2) && date[0].is_ascii() {
        NaiveDate::parse_from_str(&format!("{} {}", s, year), "%B %d %Y")
            .map(|x| x.and_hms(0, 0, 0))
            .map(|x| Local.from_local_datetime(&x))
            .map_err(|e| e.to_string())
            .map(|x| x.unwrap().with_timezone(x.unwrap().offset()))
    } else if date.len().eq(&3) && date[0].is_ascii() {
        Local.datetime_from_str(&format!("{} {} {} {}", date[0], date[1], year, date[2]), "%B %d %Y %T")
            .map(|x| x.with_timezone(x.offset()))
            .map_err(|e|e.to_string())
    } else {
        Err("failed syslog format parsing".to_string())
    }
}

/// Checks if the last characters are alphabet and assumes it to be TimeZone
/// and returns the tuple of (date_part, timezone_part)
fn is_tz_alpha(s: &str) -> Option<(&str, &str)> {
    let mut dtz = s.trim().rsplitn(2, ' ');
    let tz = dtz.next().unwrap_or_default();
    let dt = dtz.next().unwrap_or_default();
    if tz.chars().all(char::is_alphabetic) {
        Some((dt, tz))
    } else {
        None
    }
}

/// Convert the given date/time and timezone information into RFC 2822 format
fn to_rfc2822(s: &str, tz: &str) -> Result<DateTime<FixedOffset>, Error> {
    NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
        .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M"))
        .and_then(|x| {
            DateTime::parse_from_rfc2822(
                (x.format("%a, %d %b %Y %H:%M:%S").to_string() + " " + tz).as_str(),
            )
        })
        .map_err(|e| e.to_string())
}

/// converts date/time string from having '.' or '/' to '-'
/// eg: 12/13/2000 to 12-13-2000 or 12/13/2000 12:12:12.14 to 12-13-2000 12:12:12.14
fn standardize_date(s: &str) -> String {
    if s.len() < 8 {
        s.to_string()
    } else {
        s.chars()
            .into_iter()
            .take(8)
            .map(|mut x| {
                if x.eq(&'.') || x.eq(&'/') {
                    x = '-'
                };
                x
            })
            .collect::<String>()
            + &s[8..]
    }
    .replace(" UTC", " GMT")
    .replace(" UT", " GMT")
}