Search code examples
daterustrust-chrono

How can I get the current weekday in Rust using the Chrono crate?


I am trying to get the current weekday in Rust using the Chrono crate.

The JavaScript equivalent would be something like this:

new Date().toLocaleDateString('en-US',{weekday: 'long'});

I am getting the current timestamp with the following code:

let current_time = chrono::offset::Local::now();

I tried to call a .weekday() method on the resulting DateTime struct unsuccessfully. I see the DateLike trait offers something of that nature in the documentation, but I find myself unable to parse the documentation and produce the corresponding code without an example.


Solution

  • The DateLike trait, which is implemented by DateTime contains a common set of methods for date components, including weekday. You can get a DateTime from a Local offset with the date method:

    use chrono::Datelike;
    
    let current_time = chrono::offset::Local::now();
    println!("{}", current_time.date().weekday());