Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 809
Peter Uhnak Avatar asked Jul 05 '16 20:07

Peter Uhnak


People also ask

How do I print datetime in a specific format?

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.

How do I remove leading zeros from a date in R?

Use %e to obtain a leading space instead of a leading zero.

What is the data type return values from Strftime ()?

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.

What can I use instead of Strftime?

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.


1 Answers

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());
like image 111
malbarbo Avatar answered Nov 07 '22 02:11

malbarbo