Duration and Calculation

Measure the elapsed time between two code sections

std cat-date-and-time

Measures std::time::Instant::elapsed⮳ since std::time::Instant::now

Calling std::time::Instant::elapsed⮳ returns a std::time::Duration⮳ that we print at the end of the example. This method will not mutate or reset the std::time::Instant⮳ object.

use std::thread;
use std::time::Duration;
use std::time::Instant;

fn expensive_function() {
    thread::sleep(Duration::from_secs(1));
}

fn main() {
    let start = Instant::now();
    expensive_function();
    let duration = start.elapsed();

    println!("Time elapsed in expensive_function() is: {:?}", duration);
}

Perform checked date and time calculations

chrono cat-date-and-time

Calculates and displays the date and time two weeks from now using chrono::Date::checked_add_signed⮳ and the date of the day before that using chrono::Date::checked_sub_signed

The methods return None if the date and time cannot be calculated.

Escape sequences that are available for the chrono::DateTime::format⮳ can be found at chrono::format::strftime⮳.

use chrono::DateTime;
use chrono::Duration;
use chrono::TimeDelta;
use chrono::Utc;

fn day_earlier(date_time: DateTime<Utc>) -> Option<DateTime<Utc>> {
    date_time.checked_sub_signed(Duration::try_days(1).unwrap())
}

fn main() {
    let now = Utc::now();
    println!("{}", now);

    let almost_three_weeks_from_now = now
        .checked_add_signed(Duration::try_weeks(2).unwrap())
        .and_then(|in_2weeks| {
            in_2weeks.checked_add_signed(Duration::try_weeks(1).unwrap())
        })
        .and_then(day_earlier);

    match almost_three_weeks_from_now {
        Some(x) => println!("{}", x),
        None => eprintln!("Almost three weeks from now overflows!"),
    }

    match now.checked_add_signed(TimeDelta::MAX) {
        Some(x) => println!("{}", x),
        None => eprintln!(
            "We can't use chrono to tell the time for the Solar System to complete more than one full orbit around the galactic center."
        ),
    }
}

Convert a local time to another timezone

chrono cat-date-and-time

Gets the local time and displays it using chrono::offset::Local::now⮳ and then converts it to the UTC standard using the chrono::DateTime::from_utc⮳ struct method. A time is then converted using the chrono::offset::FixedOffset⮳ struct and the UTC time is then converted to UTC+8 and UTC-2.

use chrono::DateTime;
use chrono::FixedOffset;
use chrono::Local;
use chrono::TimeZone;

fn main() {
    let local_time = chrono::Local::now();
    // Separate into components
    let utc_time = local_time.naive_utc();
    let offset = *local_time.offset();
    // Serialize, pass through FFI... and recreate the `DateTime`:
    let local_time_new =
        DateTime::<Local>::from_naive_utc_and_offset(utc_time, offset);
    assert_eq!(local_time, local_time_new);

    // there is also
    let _utc_time = chrono::Utc::now();

    let china_timezone = FixedOffset::east_opt(8 * 3600).unwrap();
    let rio_timezone = FixedOffset::west_opt(2 * 3600).unwrap();
    println!("Local time now is {}", local_time);
    println!("UTC time now is {}", utc_time);
    println!(
        "Time in Hong Kong now is {}",
        china_timezone.from_utc_datetime(&utc_time)
    );
    println!(
        "Time in Rio de Janeiro now is {}",
        rio_timezone.from_utc_datetime(&utc_time)
    );
}