use chrono::{DateTime, Utc};
const DEFAULT_EPOCH: &str = "Sat, 1 Jan 2022 00:00:00 +0000";
const UTC_EPOCH: &str = "Thu, 1 Jan 1970 00:00:00 +0000";
fn gen_timestamp(epoch_str: &str) -> i64 {
let epoch = DateTime::parse_from_rfc2822(epoch_str)
.expect("ERROR: Could not get timestamp epoch.");
let now = Utc::now();
now.timestamp() - epoch.timestamp()
}
fn gen_timestamp_ms(epoch_str: &str) -> i64 {
let epoch = DateTime::parse_from_rfc2822(epoch_str)
.expect("ERROR: Could not get timestamp epoch.");
let now = Utc::now();
now.timestamp_millis() - epoch.timestamp_millis()
}
pub fn timestamp() -> String {
timestamp_i64().to_string()
}
pub fn timestamp_i64() -> i64 {
gen_timestamp(DEFAULT_EPOCH)
}
pub fn timestamp_utc() -> String {
timestamp_utc_i64().to_string()
}
pub fn timestamp_utc_i64() -> i64 {
gen_timestamp(UTC_EPOCH)
}
pub fn timestamp_ms() -> String {
timestamp_ms_i64().to_string()
}
pub fn timestamp_ms_i64() -> i64 {
gen_timestamp_ms(DEFAULT_EPOCH)
}
pub fn timestamp_custom(epoch: &str) -> String {
timestamp_custom_i64(epoch).to_string()
}
pub fn timestamp_custom_i64(epoch: &str) -> i64 {
gen_timestamp(epoch)
}
pub fn timestamp_ms_custom(epoch: &str) -> String {
timestamp_ms_custom_i64(epoch).to_string()
}
pub fn timestamp_ms_custom_i64(epoch: &str) -> i64 {
gen_timestamp_ms(epoch)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gen_timestamp() {
let epoch = DateTime::parse_from_rfc2822(DEFAULT_EPOCH)
.expect("Failed to parse epoch string");
let result = gen_timestamp(DEFAULT_EPOCH);
let now = Utc::now();
let expected = now.timestamp() - epoch.timestamp();
assert_eq!(result, expected);
}
}