Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format std::time output

Tags:

I want to display the current time in a certain format.

I am trying to avoid the time crate since it's flagged as deprecated on its the GitHub repo.

I want to use this exact format time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap() using std::time, but it doesn't seems to have a strftime.

like image 847
bl4ckb0ne Avatar asked Aug 15 '16 15:08

bl4ckb0ne


People also ask

How do you format date and time?

On the Home tab, click the Dialog Box Launcher next to Number. You can also press CTRL+1 to open the Format Cells dialog box. In the Category box, click Date or Time, and then choose the number format that is closest in style to the one you want to create.

How do I format a date string?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.

What is the DateTime format in C#?

Format. Result. DateTime.Now.ToString("MM/dd/yyyy") 05/29/2015. DateTime.Now.ToString("dddd, dd MMMM yyyy")


2 Answers

You can use the crate chrono to achieve the same result:

extern crate chrono;

use chrono::Local;

fn main() {
    let date = Local::now();
    println!("{}", date.format("%Y-%m-%d][%H:%M:%S"));
}

Edit:

The time crate is not deprecated: it is unmaintained.

Besides, it is not possible to format a time using only the standard library.

like image 95
antoyo Avatar answered Sep 21 '22 13:09

antoyo


There are (currently) two now methods: Instant::now and SystemTime::now.

Instant says:

A measurement of a monotonically increasing clock. Opaque and useful only with Duration.

SystemTime says:

A measurement of the system clock, useful for talking to external entities like the file system or other processes.

Neither of these is truly appropriate for showing to a human. Time is hard, and formatting time is additional complexity. It's really a good thing that it's not part of the standard library, otherwise it would have a fixed API that couldn't be improved.

As mentioned elsewhere, I'd recommend using chrono, the heir apparent to the time crate.

like image 27
Shepmaster Avatar answered Sep 17 '22 13:09

Shepmaster