DEV Community

Raeisi
Raeisi

Posted on

Human readable time in Rust

When it comes to formatting time into the human-readable format in Rust, there could be various possible solutions including doing some math or using Instance. However, I demonstrate the millisecond crate, the dedicated and specialized crate for the purpose. This crate converts nanoseconds, microseconds, milliseconds, seconds, etc into short and long formats; suitable for human eyes.

Imagine we have a variable containing a milliseconds value like 33023448000, computed somewhere in our code, and we want to show users the tangible equivalent result like 1 year 17 days 5 hours 10 minutes 48 seconds or a compact version 1y 17d 5h 10m 48s. Here the millisecond crate plays its role.

Project setup

First, ensure you have installed Rust and Cargo on your system and they are available in Terminal (CMD on Windows).

1. Create project

Run the following command to initialize an empty binary project:

cargo init my-millisecond --bin && cd my-millisecond
Enter fullscreen mode Exit fullscreen mode

2. Install millisecond crate

At the moment, the latest version of the crates is 0.3.

cargo add millisecond@0.3
Enter fullscreen mode Exit fullscreen mode

3. Use the crate

Open src/main.rs and write the following code:

use millisecond::Millisecond;

fn main() {
    let computed_millis = 33023448000;
    let ms = Millisecond::from_millis(computed_millis);
    println!("{ms}"); // results in: 1y 17d 5h 10m 48s
}
Enter fullscreen mode Exit fullscreen mode

4. Run the project

cargo run
Enter fullscreen mode Exit fullscreen mode

output:

~/my-millisecond$ cargo run
   Compiling my-millisecond v0.1.0 (~/my-millisecond)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
     Running `target/debug/my-millisecond`
1y 17d 5h 10m 48s
Enter fullscreen mode Exit fullscreen mode

I used the default formatting function (Display) in the example. You can use the strict method of ms.to_short_string() instead, or use ms.to_long_string() to print the long version of the output.

use millisecond::Millisecond;

fn main() {
    let computed_millis = 33023448000;
    let ms = Millisecond::from_millis(computed_millis);
    println!("default: {ms}"); // 1y 17d 5h 10m 48s
    println!("  short: {}", ms.to_short_string()); // 1y 17d 5h 10m 48s
    println!("   long: {}", ms.to_long_string()); // 1 year 17 days 5 hours 10 minutes 48 seconds
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Converting time into a human-readable format can be challenging in Rust. The millisecond crate provides a better way to overcome the situation. It is easy to use, has zero dependencies, is suitable for embedded environments, and is built up with the no_std attribute. The crate follows the MIT license and is inspired by pretty-ms the NPM package.

References

Repository: https://crates.io/crates/millisecond
The source code at Github: https://github.com/raeisimv/millisecond

Top comments (0)