Skip to content

介绍

标准库没有提供将时间戳直接格式化为日期字符串的API, 所以需要 chrono, 它支持使用 serde 序列化

rust
use chrono::{Datelike, Local, Timelike, Utc};

fn main() {
    let now = Utc::now();
    println!("{}", now); // 2024-10-28 06:11:00.508438 UTC

    let now = Local::now();
    println!("{}", now); // 2024-10-28 14:11:00.506310 +08:00
    // Utc 和 Local 获取的时间时区不同

    // format to string
    let time_str = now.format("%Y-%m-%d %H:%I:%S");
    println!("{}", time_str);

    // year
    let year = now.year();
    println!("year={}", year);

    // month
    let month = now.month();
    println!("month={}", month);

    // date
    let date = now.day();
    println!("date={}", date);

    // hour
    let hour = now.hour();
    println!("hour={}", hour);

    // minutes
    let minutes = now.minute();
    println!("minutes={}", minutes);

    // seconds
    let seconds = now.second();
    println!("seconds={}", seconds);

    // weekday
    let weekday = now.weekday().number_from_monday();
    println!("weekday={}", weekday);
}
toml
[dependencies]
chrono = "0.4.38"

Released under the MIT License.