From 3280123d223e21e71dd0313d96206af50de5f262 Mon Sep 17 00:00:00 2001 From: Trevor Merritt Date: Wed, 23 Jul 2025 08:54:29 -0400 Subject: [PATCH] Adds Duration to String for converting a duration to a human readable length of time --- src/duration_to_string.rs | 36 ++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 37 insertions(+) create mode 100644 src/duration_to_string.rs diff --git a/src/duration_to_string.rs b/src/duration_to_string.rs new file mode 100644 index 0000000..2c0ac2f --- /dev/null +++ b/src/duration_to_string.rs @@ -0,0 +1,36 @@ +use std::time::Duration; + +pub fn duration_to_string(to_convert: Duration) -> String { + let mut total_seconds = to_convert.as_secs() as u32; + let mut working_string = String::new(); + + if total_seconds > 86400 { + // days + let num_days = (total_seconds / SECONDS_IN_DAY) as u32; + working_string = format!("{} days", num_days); + total_seconds = total_seconds - (num_days * SECONDS_IN_DAY); + } + + if total_seconds > 3600 { + // hours + let num_hours = (total_seconds / SECONDS_IN_HOUR) as u32; + if num_hours > 0 { + working_string = format!("{} {} hours", working_string, num_hours); + total_seconds = total_seconds - (num_hours * SECONDS_IN_HOUR); + } + } + if total_seconds > 60 { + let num_minutes = (total_seconds / SECONDS_IN_MINUTE) as u32; + if num_minutes > 0 { + working_string = format!("{} {} minutes", working_string, num_minutes); + total_seconds = total_seconds - (num_minutes * SECONDS_IN_MINUTE); + } + // minutes + } + + + working_string = format!("{} {} seconds", working_string, total_seconds); + + working_string +} + diff --git a/src/lib.rs b/src/lib.rs index 2ae9027..b955d31 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ pub mod number_system_conversion; pub mod test_compression; pub mod data_to_text; +pub mod duration_to_string;