rustfs_rsc/
time.rs

1//! Time formatter for S3 APIs.
2use chrono::{DateTime, Utc};
3use serde::{Deserialize, Deserializer, Serialize};
4
5/// wrap of `chrono::Utc`
6#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
7pub struct UtcTime(DateTime<Utc>);
8
9impl UtcTime {
10    #[inline]
11    pub fn new(datetime: DateTime<Utc>) -> Self {
12        Self(datetime)
13    }
14
15    /// Returns current utc time
16    #[inline]
17    pub fn now() -> Self {
18        Self::new(Utc::now())
19    }
20
21    #[inline]
22    pub(crate) fn before(&self, timestamp: i64) -> bool {
23        timestamp < self.0.timestamp()
24    }
25
26    /// format date to ISO8601, like`2023-09-10T08:26:43.296Z`
27    #[inline]
28    pub fn format_time(&self) -> String {
29        self.0.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
30    }
31
32    /// format date to ISO8601, like`20230910T082643Z`
33    ///
34    /// Used in S3 signatures.
35    #[inline]
36    pub fn aws_format_time(&self) -> String {
37        self.0.format("%Y%m%dT%H%M%SZ").to_string()
38    }
39
40    /// format date to aws date.
41    ///
42    /// Used in S3 signatures
43    #[inline]
44    pub fn aws_format_date(&self) -> String {
45        self.0.format("%Y%m%d").to_string()
46    }
47}
48
49impl From<DateTime<Utc>> for UtcTime {
50    fn from(datetime: DateTime<Utc>) -> Self {
51        Self::new(datetime)
52    }
53}
54
55impl Default for UtcTime {
56    /// default: current utc time.
57    fn default() -> Self {
58        Self::now()
59    }
60}
61
62/// format date to ISO8601
63#[inline]
64pub fn aws_format_time(t: &UtcTime) -> String {
65    t.0.format("%Y%m%dT%H%M%SZ").to_string()
66}
67
68/// format date to aws date
69#[inline]
70pub fn aws_format_date(t: &UtcTime) -> String {
71    t.0.format("%Y%m%d").to_string()
72}
73
74pub fn deserialize_with_str<'de, D>(deserializer: D) -> Result<UtcTime, D::Error>
75where
76    D: Deserializer<'de>,
77{
78    let value = <DateTime<Utc>>::deserialize(deserializer)?;
79    Ok(UtcTime::new(value))
80}