Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Duration と計算

2 つのコードセクション間の経過時間を測定する

std-badge cat-time-badge

time::Instant::now からの time::Instant::elapsed を測定します。

time::Instant::elapsed を呼び出すと time::Duration が返され、これを例の最後で出力します。 このメソッドは time::Instant オブジェクトを変更したりリセットしたりしません。

use std::time::{Duration, Instant};
use std::thread;

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);
}

日付と時刻のチェック付き計算を行う

chrono-badge cat-date-and-time-badge

DateTime::checked_add_signed を使用して今から 2 週間後の日付と時刻を計算して表示し、DateTime::checked_sub_signed を使用してその前日の日付を計算して表示します。日付と時刻を計算できない場合、これらのメソッドは None を返します。

DateTime::format で使用できるエスケープシーケンスは chrono::format::strftime にあります。

use chrono::{DateTime, Duration, Utc};

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

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

    let almost_three_weeks_from_now = now.checked_add_signed(Duration::weeks(2))
            .and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::weeks(1)))
            .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(Duration::max_value()) {
        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."),
    }
}

ローカル時刻を別のタイムゾーンに変換する

chrono-badge cat-date-and-time-badge

offset::Local::now を使用してローカル時刻を取得して表示し、その後 DateTime::from_utc 構造体メソッドを使用して UTC 標準時に変換します。次に、offset::FixedOffset 構造体を使用して時刻を変換し、UTC 時刻を UTC+8 と UTC-2 に変換します。

use chrono::{DateTime, FixedOffset, Local, Utc};

fn main() {
    let local_time = Local::now();
    let utc_time = DateTime::<Utc>::from_utc(local_time.naive_utc(), Utc);
    let china_timezone = FixedOffset::east(8 * 3600);
    let rio_timezone = FixedOffset::west(2 * 3600);
    println!("Local time now is {}", local_time);
    println!("UTC time now is {}", utc_time);
    println!(
        "Time in Hong Kong now is {}",
        utc_time.with_timezone(&china_timezone)
    );
    println!("Time in Rio de Janeiro now is {}", utc_time.with_timezone(&rio_timezone));
}