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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Peter Uhnak
  • 9,617
  • 5
  • 38
  • 51
  • I think the [chrono crate](https://lifthrasiir.github.io/rust-chrono/chrono/format/strftime/index.html) has support for that specifier. – squiguy Jul 05 '16 at 21:10

1 Answers1

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());
jhpratt
  • 6,841
  • 16
  • 40
  • 50
malbarbo
  • 10,717
  • 1
  • 42
  • 57