pub use chrono::{
DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc,
Weekday,
};
#[inline]
pub fn datetime(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> Option<DateTime<Utc>> {
Utc.with_ymd_and_hms(year, month, day, hour, minute, second)
.single()
}
#[inline]
pub fn datetime_utc(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> DateTime<Utc> {
datetime(year, month, day, hour, minute, second).expect("Invalid datetime components")
}
#[inline]
pub fn try_datetime_utc(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> Option<DateTime<Utc>> {
datetime(year, month, day, hour, minute, second)
}
#[inline]
pub fn date(year: i32, month: u32, day: u32) -> Option<DateTime<Utc>> {
datetime(year, month, day, 0, 0, 0)
}
#[inline]
pub fn now() -> DateTime<Utc> {
Utc::now()
}
#[inline]
pub fn hours_ago(hours: i64) -> DateTime<Utc> {
Utc::now() - Duration::hours(hours)
}
#[inline]
pub fn days_ago(days: i64) -> DateTime<Utc> {
Utc::now() - Duration::days(days)
}
#[inline]
pub fn weeks_ago(weeks: i64) -> DateTime<Utc> {
Utc::now() - Duration::weeks(weeks)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_datetime() {
let dt = datetime(2024, 1, 15, 14, 30, 0).unwrap();
assert_eq!(dt.year(), 2024);
assert_eq!(dt.month(), 1);
assert_eq!(dt.day(), 15);
assert_eq!(dt.hour(), 14);
assert_eq!(dt.minute(), 30);
assert_eq!(dt.second(), 0);
}
#[test]
fn test_datetime_invalid() {
assert!(datetime(2024, 13, 1, 0, 0, 0).is_none()); assert!(datetime(2024, 1, 32, 0, 0, 0).is_none()); assert!(datetime(2024, 1, 1, 25, 0, 0).is_none()); }
#[test]
fn test_date() {
let dt = date(2024, 6, 15).unwrap();
assert_eq!(dt.hour(), 0);
assert_eq!(dt.minute(), 0);
}
#[test]
fn test_now() {
let n = now();
assert!(n.year() >= 2024);
}
#[test]
fn test_hours_ago() {
let one_hour_ago = hours_ago(1);
let n = now();
let diff = n - one_hour_ago;
assert!(diff.num_minutes() >= 59 && diff.num_minutes() <= 61);
}
#[test]
fn test_days_ago() {
let yesterday = days_ago(1);
let n = now();
let diff = n - yesterday;
assert!(diff.num_hours() >= 23 && diff.num_hours() <= 25);
}
use chrono::Datelike;
use chrono::Timelike;
#[test]
fn test_datetime_utc() {
let dt = datetime_utc(2024, 1, 15, 14, 30, 0);
assert_eq!(dt.year(), 2024);
}
#[test]
fn test_try_datetime_utc() {
assert!(try_datetime_utc(2024, 1, 15, 14, 30, 0).is_some());
assert!(try_datetime_utc(2024, 13, 15, 14, 30, 0).is_none());
}
}