mod tokens;
pub use tokens::Token;
use chrono::DateTime;
use tokens::render_token;
pub fn format_php<Tz: chrono::TimeZone>(dt: &DateTime<Tz>, format: &str) -> String
where
Tz::Offset: std::fmt::Display,
{
let mut out = String::with_capacity(format.len() + 8);
let mut chars = format.chars().peekable();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
continue;
}
if let Some(token) = Token::from_char(c) {
render_token(dt, token, &mut out);
} else {
out.push(c);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{DateTime, FixedOffset, TimeZone, Utc};
#[test]
fn escapes_literals() {
let dt = Utc.with_ymd_and_hms(2001, 3, 10, 17, 16, 18).unwrap();
assert_eq!(format_php(&dt, r"\Y-\m-\d"), "Y-m-d");
assert_eq!(format_php(&dt, r"l \t\h\e jS"), "Saturday the 10th");
}
#[test]
fn common_patterns() {
let dt = Utc.with_ymd_and_hms(2001, 3, 10, 17, 16, 18).unwrap();
assert_eq!(format_php(&dt, "Y-m-d H:i:s"), "2001-03-10 17:16:18");
assert_eq!(format_php(&dt, "m.d.y"), "03.10.01");
assert_eq!(format_php(&dt, "j, n, Y"), "10, 3, 2001");
assert_eq!(format_php(&dt, "Ymd"), "20010310");
assert_eq!(format_php(&dt, "H:i:s"), "17:16:18");
assert_eq!(format_php(&dt, "F j, Y, g:i a"), "March 10, 2001, 5:16 pm");
assert_eq!(format_php(&dt, "U"), dt.timestamp().to_string());
}
#[test]
fn iso_and_rfc() {
let dt = Utc.with_ymd_and_hms(2000, 7, 1, 0, 0, 0).unwrap();
assert_eq!(format_php(&dt, "c"), "2000-07-01T00:00:00+00:00");
assert_eq!(format_php(&dt, "r"), "Sat, 01 Jul 2000 00:00:00 +0000");
}
#[test]
fn with_offset() {
let tz = FixedOffset::west_opt(7 * 3600).unwrap(); let dt = tz.with_ymd_and_hms(2001, 3, 10, 17, 16, 18).unwrap();
assert_eq!(
format_php(&dt, "Y-m-d H:i:s O"),
"2001-03-10 17:16:18 -0700"
);
assert_eq!(format_php(&dt, "P"), "-07:00");
assert_eq!(format_php(&dt, "p"), "-07:00");
assert_eq!(format_php(&dt, "Z"), (-(7 * 3600)).to_string());
}
#[test]
fn empty_and_trailing_backslash() {
let dt = Utc.with_ymd_and_hms(2001, 1, 1, 0, 0, 0).unwrap();
assert_eq!(format_php(&dt, ""), "");
assert_eq!(format_php(&dt, r"Y\"), "2001");
assert_eq!(format_php(&dt, r"\\"), r"\");
}
#[test]
fn subsecond_format_string() {
let dt = DateTime::from_timestamp(1_124_121_121, 987_654_321).unwrap();
assert_eq!(format_php(&dt, "u"), "987654");
assert_eq!(format_php(&dt, "v"), "987");
assert_eq!(
format_php(&dt, "Y-m-d\\TH:i:s.vP"),
"2005-08-15T15:52:01.987+00:00"
);
}
}