humantime icon indicating copy to clipboard operation
humantime copied to clipboard

Extend format_duration with rounding to milliseconds, seconds, minutes, hours, days, month and years

Open flxo opened this issue 2 years ago • 4 comments

Sometimes displaying durations in their full precision is not needed and counter productive. Especially in logs where the quantity of a duration is in a seconds/minute/hour range the formatting of ms, us and ns might want to be omitted.

The boilerplate workaround I did some times is (beside creating a trait and blah blah...) is to do something like

format_duration(Duration::from_secs(duration.as_secs());

to get rid of the subsec part.

A possible extension could look like

/// Formats duration into a human-readable string with second precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use humantime::format_duration;
///
/// let val = Duration::new(9420, 1_000_000);
/// assert_eq!(format_duration_secs(val).to_string(), "2h 37m");
/// ```
pub fn format_duration_secs(val: Duration) -> FormattedDuration { ... }

/// ...
pub fn format_duration_min(val: Duration) -> FormattedDuration { ... }

/// ...
pub fn format_duration_hour(val: Duration) -> FormattedDuration { ... }
...

If applicable I happily file a PR.

thanks

flxo avatar Jan 10 '23 08:01 flxo

I would find this feature very useful as well.

Perhaps for logging it would then be even more useful to allow a duration to be formatted to only the most significant precision, i.e. if more than an hour in terms of hours, if more than a minute but less than hours in terms of minutes, etc. For application where precision is not required and you wish to give the user only a rough indication of time, like for some logging cases I think only the most significant time indicator would be the easiest to read.

VinciTec avatar Apr 02 '23 14:04 VinciTec

Thanks for the workaround, I came into the crate's repo to find how to do just this.

RobertGauld avatar Sep 25 '23 09:09 RobertGauld

This could use the Formatter::precision, e.g. format!("{0:.1} | {0:.2} | {0}", humantime::format_duration(Duration::from_secs(3661))) could be "1h | 1h 1m | 1h 1m 1s".

Nemo157 avatar Oct 21 '23 09:10 Nemo157