from_system_time

Function from_system_time 

Source
pub fn from_system_time(time: SystemTime) -> Result<TimeStamp, Error>
Expand description

Convert a std::time::SystemTime to a UNIX timestamp in seconds.

This function converts a std::time::SystemTime instance to a TimeStamp (Unix timestamp in seconds). It handles the conversion and error cases related to negative timestamps or other time conversion issues.

§Examples

use std::time::{SystemTime, UNIX_EPOCH, Duration};

// Convert the current system time to a timestamp
let system_time = SystemTime::now();
let timestamp = time_format::from_system_time(system_time).unwrap();

// Convert a specific time
let past_time = UNIX_EPOCH + Duration::from_secs(1500000000);
let past_timestamp = time_format::from_system_time(past_time).unwrap();
assert_eq!(past_timestamp, 1500000000);

§Working with Time Components

You can use the function to convert a SystemTime to components:

use std::time::{SystemTime, UNIX_EPOCH, Duration};

// Create a specific time: January 15, 2023 at 14:30:45 UTC
let specific_time = UNIX_EPOCH + Duration::from_secs(1673793045);

// Convert to timestamp
let ts = time_format::from_system_time(specific_time).unwrap();

// Get the time components
let components = time_format::components_utc(ts).unwrap();

// Verify the time components
assert_eq!(components.year, 2023);
assert_eq!(components.month, 1); // January
assert_eq!(components.month_day, 15);
assert_eq!(components.hour, 14);
assert_eq!(components.min, 30);
assert_eq!(components.sec, 45);

§Formatting with strftime

Convert a SystemTime and format it as a string:

use std::time::{SystemTime, UNIX_EPOCH, Duration};

// Create a specific time
let specific_time = UNIX_EPOCH + Duration::from_secs(1673793045);

// Convert to timestamp
let ts = time_format::from_system_time(specific_time).unwrap();

// Format as ISO 8601
let iso8601 = time_format::format_iso8601_utc(ts).unwrap();
assert_eq!(iso8601, "2023-01-15T14:30:45Z");

// Custom formatting
let custom_format = time_format::strftime_utc("%B %d, %Y at %H:%M:%S", ts).unwrap();
assert_eq!(custom_format, "January 15, 2023 at 14:30:45");