use crate::format::format_php;
use chrono::{DateTime, Local, TimeZone, Utc};
pub fn time() -> i64 {
Utc::now().timestamp()
}
pub fn date(format: &str) -> String {
format_php(&Local::now(), format)
}
pub fn date_with(format: &str, timestamp: i64) -> String {
let dt = local_from_timestamp(timestamp);
format_php(&dt, format)
}
pub fn gmdate(format: &str) -> String {
format_php(&Utc::now(), format)
}
pub fn gmdate_with(format: &str, timestamp: i64) -> String {
let dt = utc_from_timestamp(timestamp);
format_php(&dt, format)
}
fn utc_from_timestamp(timestamp: i64) -> DateTime<Utc> {
DateTime::from_timestamp(timestamp, 0).unwrap_or_else(|| {
DateTime::from_timestamp(0, 0).unwrap()
})
}
fn local_from_timestamp(timestamp: i64) -> DateTime<Local> {
match Local.timestamp_opt(timestamp, 0) {
chrono::LocalResult::Single(dt) | chrono::LocalResult::Ambiguous(dt, _) => dt,
chrono::LocalResult::None => Local
.timestamp_opt(0, 0)
.single()
.unwrap_or_else(Local::now),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gmdate_fixed() {
let ts = Utc
.with_ymd_and_hms(2001, 3, 10, 17, 16, 18)
.unwrap()
.timestamp();
assert_eq!(gmdate_with("Y-m-d H:i:s", ts), "2001-03-10 17:16:18");
assert_eq!(gmdate_with("l jS", ts), "Saturday 10th");
assert_eq!(gmdate_with("U", ts), ts.to_string());
}
#[test]
fn time_is_reasonable() {
let t = time();
assert!(t > 1_000_000_000);
}
#[test]
fn date_returns_non_empty() {
assert!(!date("Y").is_empty());
assert!(!gmdate("Y-m-d").is_empty());
}
}