在Rust中获取精准时间的正确方法是什么?
Rust中获取正确时间的方法及问题排查
问题根源:格式化字符串错误
你代码里的时间格式化用了%m,这个占位符代表的是月份(01-12),而不是分钟!当前是1月,所以输出里的01是月份值,不是实际的分钟数(实际是08)。正确的分钟占位符是%M。
修正后的代码
use chrono::{DateTime, Local, Utc}; use std::time::SystemTime; fn main() { println!( "Local.now() {}", Local::now().format("%H:%M:%S").to_string() ); println!("Utc.now() {}", Utc::now().format("%H:%M:%S").to_string()); let system_time = SystemTime::now(); let stime: DateTime<Utc> = system_time.into(); println!("SystemTime.now() {}", stime.format("%H:%M:%S")); }
运行结果验证
修正后再运行,输出就会和date命令的结果匹配:
$ date && target/debug/mybin
Sun Jan 15 04:08:19 PM CET 2023
Local.now() 16:08:19
Utc.now() 15:08:19
SystemTime.now() 15:08:19
Rust获取正确时间的核心要点
- 选择合适的时间库:
chrono是Rust生态中常用的时间处理库,支持本地时间、UTC时间的格式化和转换,比标准库的SystemTime更易用。 - 牢记格式化占位符:
%H:24小时制小时(00-23)%M:分钟(00-59)%S:秒(00-59)%m:月份(01-12)%d:日期(01-31)
- 区分时间类型:
Local::now():获取当前系统的本地时间(带时区)Utc::now():获取UTC标准时间SystemTime::now():标准库提供的系统时间,可转换为chrono的DateTime类型使用
内容的提问来源于stack exchange,提问作者GlinesMome
相关产品推荐
相关产品推荐

