ark-api 0.17.0-pre.15

Ark API
Documentation
//! # ⌚ Time API
//!
//! This API provides functionality to query and format (for display) the real world time.
//!
//! Simple example:
//!
//! ```rust
//! require_time_api!();
//!
//! let now = time().now();
//! log::info!("Now: {}", time().format_instant_for_display(now, TimeFormat::ISODateTime));
//! ```

use crate::ffi::time_v1 as ffi;

pub use ffi::TimeFormat;
#[doc(hidden)]
pub use ffi::API as FFI_API;

/// The time api gives you access to real world time functionality.
#[derive(Copy, Clone)]
pub struct Time {}

/// An instant in time, internally represented as nanoseconds since the UNIX epoch (1970-01-01).
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
#[cfg_attr(feature = "with_serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "with_speedy", derive(speedy::Writable, speedy::Readable))]
pub struct Instant(i64);

impl std::fmt::Debug for Instant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Time {}
            .format_instant_for_display(*self, TimeFormat::ISODateTimeUTC)
            .fmt(f)
    }
}

impl Instant {
    /// From nanoseconds elapses since the UNIX epoch (1970-01-01).
    pub fn from_nanos_since_epoch(ns_since_epoch: i64) -> Self {
        Self(ns_since_epoch)
    }

    /// Convert to nanoseconds elapses since the UNIX epoch (1970-01-01).
    pub fn as_nanos_since_epoch(self) -> i64 {
        self.0
    }
}

// Duration might come later.

impl Time {
    /// UTC time.
    pub fn now(self) -> Instant {
        Instant(ffi::time_utc())
    }

    /// Takes an UTC time returned from `now()`, and formats it into a displayable string.
    ///
    /// The exact contents of the string can depend on the locale - so DO NOT try to parse the
    /// contents, only display it directly.
    pub fn format_instant_for_display(self, i: Instant, format: TimeFormat) -> String {
        ffi::format_time_for_display(i.0, format)
    }
}