如何在Rust示例中获得本地和UTC的当前日期和时间

1,589 阅读1分钟

这个程序打印出系统中的当前日期和时间以及UTC时区。它使用Chrono库来访问当前的时间戳相关信息。让我们使用cargo命令创建一个新的rust项目。接下来,将目录改为dateapp,在cargo.toml文件中添加Chrono的依赖关系

[dependencies]
chrono = "0.4"

现在,运行cargo build命令来安装所有的依赖项。

让我们写一段代码,以本地和UTC格式打印日期。

Rust Current Date and time in

Utc::now(): 返回包含UTC日期和时间的DateTime 对象Local::now(): 返回包含系统日期和时间的DateTime 对象

下面是一个示例程序

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

fn main() {
    let utc: DateTime = Utc::now();
    let local: DateTime = Local::now();
    println!("Current Date and Time in UTC {:?}", utc);
    println!("Current Date and Time in System {:?}", utc);
}

使用cargo run 运行上述代码。

PS A:\work\rust\dateapp> cargo run
   Compiling dateapp v0.1.0 (A:\work\rust\dateapp)
    Finished dev [unoptimized + debuginfo] target(s) in 1.56s
     Running `target\debug\dateapp.exe`
Current Date and Time in UTC 2022-04-29T10:53:01.715904300Z
Current Date and Time in System 2022-04-29T16:23:01.715941800+05:30