Skip to main content

steamkit/util/
date_utils.rs

1//! Converting between Unix timestamps and [`SystemTime`].
2
3use std::time::{Duration, SystemTime, UNIX_EPOCH};
4
5use crate::error::SteamError;
6
7/// The largest timestamp we accept: `9999-12-31T23:59:59Z`.
8const MAX_UNIX_SECONDS: u64 = 253_402_300_799;
9
10/// Converts a Unix timestamp to a point in time. Same as
11/// [`DateUtils::date_time_from_unix_time`].
12pub fn date_time_from_unix_time(unix_time: u64) -> Result<SystemTime, SteamError> {
13    DateUtils::date_time_from_unix_time(unix_time)
14}
15
16/// Converts a point in time to a Unix timestamp. Same as
17/// [`DateUtils::date_time_to_unix_time`].
18pub fn date_time_to_unix_time(time: SystemTime) -> Result<u64, SteamError> {
19    DateUtils::date_time_to_unix_time(time)
20}
21
22/// Date helpers.
23#[derive(Debug)]
24pub struct DateUtils;
25
26impl DateUtils {
27    /// Converts a Unix timestamp (seconds) to a point in time. Timestamps after
28    /// the year 9999 are an error.
29    pub fn date_time_from_unix_time(unix_time: u64) -> Result<SystemTime, SteamError> {
30        if unix_time > MAX_UNIX_SECONDS {
31            return Err(SteamError::InvalidArgument(format!(
32                "The unix timestamp {unix_time} is outside of the representable date range."
33            )));
34        }
35
36        Ok(UNIX_EPOCH + Duration::from_secs(unix_time))
37    }
38
39    /// Converts a point in time to a Unix timestamp (seconds), truncating any
40    /// fraction. Times before the epoch are an error.
41    pub fn date_time_to_unix_time(time: SystemTime) -> Result<u64, SteamError> {
42        match time.duration_since(UNIX_EPOCH) {
43            Ok(duration) => Ok(duration.as_secs()),
44            Err(error) => Err(SteamError::InvalidArgument(format!(
45                "The date is before the unix epoch ({} seconds before it).",
46                error.duration().as_secs()
47            ))),
48        }
49    }
50}