12

How can I print a date/time without leading zeros? For example, Jul 5, 9:15.

According to the docs it uses the same syntax as strftime, however suppressing leading zeros

time::strftime("%b %-d, %-I:%M", &time::now()).unwrap()

leads to an error:

thread '' panicked at 'called Result::unwrap() on an Err value: InvalidFormatSpecifier('-')', ../src/libcore/result.rs:746

I suspect Rust doesn't support the glibc extensions that provide this flag (and several others); however there is no syntax for non-prefixed date/time; the alternative (%l) just prefixes with blank space which is equally useless.

I could create the string by hand, but that defeats the purpose of the function.

1
  • I think the chrono crate has support for that specifier.
    – squiguy
    Commented Jul 5, 2016 at 21:10

1 Answer 1

18

Looking the code we can confirm that time crate does not support the flag -.


That said, I recommend you use the chrono crate. In addition to supporting the format specifiers you want, the chrono crate also has support for timezones and much more.

let now = chrono::Utc::now();
println!("{}", now.format("%b %-d, %-I:%M").to_string());
2
  • I'm getting "Could not find UTC in chrono" when using this code. Any suggestions? Commented May 13, 2018 at 9:58
  • Figured it out, UTC is actually Utc Commented May 13, 2018 at 10:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.