unixrustrust-chrono

Correct way to get accurate time in Rust?


I'm trying to get accurate time with:

use chrono::{DateTime, Local, Utc};
use std::time::SystemTime;

fn main() {
    println!(
        "Local.now() {}",
        Local::now().format("%H:%m:%S").to_string()
    );
    println!("Utc.now() {}", Utc::now().format("%H:%m:%S").to_string());
    let system_time = SystemTime::now();
    let stime: DateTime<Utc> = system_time.into();
    println!("SystemTime.now() {}", stime.format("%H:%m:%S"));
}

However, if I run it:

$ date && target/debug/mybin
Sun Jan 15 04:08:19 PM CET 2023
Local.now() 16:01:19
Utc.now() 15:01:19
SystemTime.now() 15:01:19

I don't know where comes from the shift, but I want to know what's the correct way to get the right time?


Solution

  • The %m token inserts the current month's number, which is 1 because it is January. You probably want %M instead, which inserts the minute number. So you are correctly obtaining the current time, but are incorrectly displaying it by using the month number in the place where you'd expect to see the minute number.

    See chrono's strftime documentation for a complete list of formatting codes.