use serde::{Deserialize, Serialize};
use std::fmt;
use super::{DateTime, Utc};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UnixTimestamp(pub i64);
impl UnixTimestamp {
pub fn new(seconds: i64) -> Self {
Self(seconds)
}
pub fn now() -> Self {
Self(chrono::Utc::now().timestamp())
}
pub fn from_datetime(dt: DateTime<Utc>) -> Self {
Self(dt.timestamp())
}
pub fn to_datetime(self) -> Option<DateTime<Utc>> {
chrono::DateTime::from_timestamp(self.0, 0)
}
pub fn as_seconds(&self) -> i64 {
self.0
}
pub fn is_past(&self) -> bool {
self.0 < chrono::Utc::now().timestamp()
}
pub fn is_future(&self) -> bool {
self.0 > chrono::Utc::now().timestamp()
}
}
impl Default for UnixTimestamp {
fn default() -> Self {
Self::now()
}
}
impl From<i64> for UnixTimestamp {
fn from(seconds: i64) -> Self {
Self(seconds)
}
}
impl From<UnixTimestamp> for i64 {
fn from(ts: UnixTimestamp) -> Self {
ts.0
}
}
impl From<DateTime<Utc>> for UnixTimestamp {
fn from(dt: DateTime<Utc>) -> Self {
Self::from_datetime(dt)
}
}
impl fmt::Display for UnixTimestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(dt) = self.to_datetime() {
write!(f, "{}", dt.format("%Y-%m-%d %H:%M:%S UTC"))
} else {
write!(f, "{}", self.0)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UnixTimestampMillis(pub i64);
impl UnixTimestampMillis {
pub fn new(millis: i64) -> Self {
Self(millis)
}
pub fn now() -> Self {
Self(chrono::Utc::now().timestamp_millis())
}
pub fn from_datetime(dt: DateTime<Utc>) -> Self {
Self(dt.timestamp_millis())
}
pub fn to_datetime(self) -> Option<DateTime<Utc>> {
chrono::DateTime::from_timestamp_millis(self.0)
}
pub fn as_millis(&self) -> i64 {
self.0
}
pub fn as_seconds(&self) -> i64 {
self.0 / 1000
}
pub fn to_unix_timestamp(self) -> UnixTimestamp {
UnixTimestamp(self.0 / 1000)
}
pub fn is_past(&self) -> bool {
self.0 < chrono::Utc::now().timestamp_millis()
}
pub fn is_future(&self) -> bool {
self.0 > chrono::Utc::now().timestamp_millis()
}
}
impl Default for UnixTimestampMillis {
fn default() -> Self {
Self::now()
}
}
impl From<i64> for UnixTimestampMillis {
fn from(millis: i64) -> Self {
Self(millis)
}
}
impl From<UnixTimestampMillis> for i64 {
fn from(ts: UnixTimestampMillis) -> Self {
ts.0
}
}
impl From<DateTime<Utc>> for UnixTimestampMillis {
fn from(dt: DateTime<Utc>) -> Self {
Self::from_datetime(dt)
}
}
impl From<UnixTimestamp> for UnixTimestampMillis {
fn from(ts: UnixTimestamp) -> Self {
Self(ts.0 * 1000)
}
}
impl fmt::Display for UnixTimestampMillis {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(dt) = self.to_datetime() {
write!(f, "{}", dt.format("%Y-%m-%d %H:%M:%S%.3f UTC"))
} else {
write!(f, "{}", self.0)
}
}
}