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 anErr
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.
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
Use %e to obtain a leading space instead of a leading zero.
What is the data type return values from Strftime ()? The strftime() method returns a string representing date and time using date, time or datetime object.
Replacements. For locale-aware date/time formatting, use IntlDateFormatter::format (requires Intl extension). In a real-life and ideal use case, the IntlDateFormatter object is instantiated once based on the user's locale information, and the object instance can is used whenever necessary.
Looking the code we can confirm that time
crate does not support the flag -
. Also note that time
crate is on rust-lang-deprecated
user, so it is being deprecated.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With