pub fn format_duration(duration: &Duration) -> StringExpand description
Formats a chrono::Duration into a standardized “HH:MM” string.
This function converts a time duration into a human-readable format suitable for display in reports, tables, and user interfaces. It ensures consistent formatting across the entire application.
§Formatting Rules
- Hours: Always displayed with at least 2 digits (zero-padded)
- Minutes: Always displayed with exactly 2 digits (zero-padded)
- Seconds: Not displayed (rounded to nearest minute)
- Negative: Treated as zero duration (“00:00”)
- Overflow: Large durations handled gracefully
§Algorithm
- Extract total hours from the duration
- Extract remaining minutes (after removing full hours)
- Clamp negative values to zero
- Format with zero-padding
§Arguments
duration- A reference to the chrono::Duration to format
§Returns
A String in “HH:MM” format representing the duration.
§Examples
use kasl::libs::formatter::format_duration;
use chrono::Duration;
// Standard durations
assert_eq!(format_duration(&Duration::hours(8)), "08:00");
assert_eq!(format_duration(&Duration::minutes(90)), "01:30");
assert_eq!(format_duration(&Duration::minutes(45)), "00:45");
// Edge cases
assert_eq!(format_duration(&Duration::zero()), "00:00");
assert_eq!(format_duration(&Duration::hours(-1)), "00:00");
assert_eq!(format_duration(&Duration::hours(24)), "24:00");§Performance Notes
This function is designed for frequent use and has minimal overhead:
- Single allocation for the result string
- Simple arithmetic operations only
- No complex parsing or validation
§Thread Safety
This function is pure and thread-safe. It can be called concurrently from multiple threads without synchronization.