How to get year, month, day etc from SystemTime

I have a SystemTime. I'd like to format it so I have something like:
01-Sep-2022 10:12:53

How should I go about it?

For the formatting the time crate can be used. Assuming you want to format it using local time zones, you can do it e.g. as follows (note that I’ve never used that crate before, so there might be nicer approaches I’m missing)

time = { version = "0.3.17", features = ["local-offset", "formatting", "macros"] }

use std::time::SystemTime;

fn main() {
    let t = std::time::SystemTime::now();


fn pretty_print_system_time(t: SystemTime) {
    let utc = time::OffsetDateTime::UNIX_EPOCH
        + time::Duration::try_from(t.duration_since(std::time::UNIX_EPOCH).unwrap()).unwrap();
    let local = utc.to_offset(time::UtcOffset::local_offset_at(utc).unwrap());
            &mut std::io::stdout().lock(),
                "[day]-[month repr:short]-[year] [hour]:[minute]:[second]\n"

Rust Explorer

20-Nov-2022 09:49:52

Also note that if you don’t have to use SystemTime for some other particular reasons (i.e. existing / other code that needs this type in particular), it might be nicer to avoid the need to akwardly convert it to time crate types and work with those from the beginning.

Hi and thank you for your help.
I have SystemTime as a result of call to std::fs::metadata on a pathbuf.
I'm working currently on file manager and I want to show the modification time of particular path.
I'm not sure if I can avoid using SystemTime in this scenario.
But I agree with you that it would be much nicer if it was possible to avoid it.
Once again, thank you for your help. I appreciate it!

One more thing, how/from where did you now how to describe the format of the time?

The documentation of format_description! links to this page, which is pretty abstract, but the “well known format descriptions” page has these “Approximate Format Description” sections which turn out to serve well as examples.

1 Like

Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.