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

Date and time arithmetic

[package]
name = "chrono-date-arithmetic"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
chrono = "0.4.26"
use chrono::{DateTime, Duration, Utc};

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

    let tomorrow = now + Duration::days(1);
    println!("{}", tomorrow);

    let yesterday = now - Duration::days(1);
    println!("{}", yesterday);

    let two_hours_later = now + Duration::hours(2);
    println!("{}", two_hours_later);
}
2023-09-18 16:22:26.308212333 UTC
2023-09-19 16:22:26.308212333 UTC
2023-09-17 16:22:26.308212333 UTC
2023-09-18 18:22:26.308212333 UTC