use chrono::{DateTime, Utc};
pub fn get_timestamp() -> i64 {
Utc::now().timestamp()
}
pub fn get_timestamp_millis() -> i64 {
Utc::now().timestamp_millis()
}
pub fn timestamp_to_string(timestamp: i64) -> String {
timestamp.to_string()
}
pub fn parse_timestamp(s: &str) -> Result<i64, std::num::ParseIntError> {
s.parse()
}
pub fn timestamp_to_datetime(timestamp: i64) -> DateTime<Utc> {
DateTime::from_timestamp(timestamp, 0).unwrap_or_default()
}
pub fn datetime_to_timestamp(dt: &DateTime<Utc>) -> i64 {
dt.timestamp()
}
pub fn is_timestamp_valid(timestamp: i64, tolerance_seconds: i64) -> bool {
let now = Utc::now().timestamp();
let diff = (now - timestamp).abs();
diff <= tolerance_seconds
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_timestamp() {
let timestamp = get_timestamp();
assert!(timestamp > 0);
assert!(timestamp > 1600000000); }
#[test]
fn test_get_timestamp_millis() {
let timestamp = get_timestamp_millis();
assert!(timestamp > 0);
assert!(timestamp > 1600000000000); }
#[test]
fn test_timestamp_to_string() {
let s = timestamp_to_string(1609459200);
assert_eq!(s, "1609459200");
}
#[test]
fn test_parse_timestamp() {
let timestamp = parse_timestamp("1609459200").unwrap();
assert_eq!(timestamp, 1609459200);
let result = parse_timestamp("invalid");
assert!(result.is_err());
}
#[test]
fn test_timestamp_to_datetime() {
let dt = timestamp_to_datetime(1609459200);
assert_eq!(dt.format("%Y-%m-%d").to_string(), "2021-01-01");
}
#[test]
fn test_datetime_to_timestamp() {
let dt = timestamp_to_datetime(1609459200);
let timestamp = datetime_to_timestamp(&dt);
assert_eq!(timestamp, 1609459200);
}
#[test]
fn test_is_timestamp_valid() {
let now = get_timestamp();
assert!(is_timestamp_valid(now, 300));
assert!(is_timestamp_valid(now - 299, 300));
assert!(!is_timestamp_valid(now - 301, 300));
assert!(!is_timestamp_valid(0, 300));
}
}