How can I print a date/time from time::strftime without leading zeros?
Asked Answered
N

1

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.

Nonparticipation answered 5/7, 2016 at 20:15 Comment(1)
I think the chrono crate has support for that specifier.Lejeune
T
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());
Terce answered 5/7, 2016 at 21:11 Comment(2)
I'm getting "Could not find UTC in chrono" when using this code. Any suggestions?Deterrence
Figured it out, UTC is actually UtcDeterrence

© 2022 - 2024 — McMap. All rights reserved.