NaiveDateTime如何生成当前的时间?
时间: 2024-04-21 19:22:46 浏览: 9
要生成当前时间的 `NaiveDateTime` 对象,你可以使用 `chrono` 库中的 `Local::now()` 方法。这个方法返回当前本地时间的 `DateTime<Local>` 对象,你可以通过将其转换为 `NaiveDateTime` 类型来获取当前的 `NaiveDateTime`。
以下是一个示例代码,演示如何生成当前时间的 `NaiveDateTime` 对象:
```rust
use chrono::{Local, NaiveDateTime};
fn main() {
let current_datetime_local = Local::now();
let current_naive_datetime: NaiveDateTime = current_datetime_local.naive_local();
println!("{:?}", current_naive_datetime);
}
```
在上面的示例中,我们使用 `Local::now()` 方法获取当前本地时间的 `DateTime<Local>` 对象。然后,我们调用 `naive_local()` 方法将其转换为 `NaiveDateTime` 类型,得到当前的 `NaiveDateTime` 对象。
最后,我们打印出 `current_naive_datetime`,以验证当前时间是否被成功生成为 `NaiveDateTime` 对象。
运行上述代码,你将会看到输出当前的 `NaiveDateTime` 值,表示成功生成了当前时间的 `NaiveDateTime` 对象。