tailhook / humantime

A parser and formatter for std::time::{SystemTime, Duration}
Apache License 2.0
283 stars 34 forks source link

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

Open flxo opened 1 year ago

flxo commented 1 year ago

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

VinciTec commented 1 year ago

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.

RobertGauld commented 9 months ago

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

Nemo157 commented 8 months ago

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".