如何在Rust的chrono库中显示不含小数秒的DateTime?
在Rust中移除chrono UTC时间的毫秒部分
直接使用{:?}打印chrono库的UTC当前时间时,输出会包含多余的毫秒小数:
println!("{:?}", chrono::offset::Utc::now());
输出示例:
2022-12-01T07:56:54.242352517Z
如果需要输出不带毫秒的格式:
2022-12-01T07:56:54Z
可以用以下两种方法实现:
方法1:自定义格式化输出
chrono支持通过format方法指定时间格式字符串,使用%Y-%m-%dT%H:%M:%SZ即可生成目标格式:
use chrono::Utc; fn main() { let current_time = Utc::now(); println!("{}", current_time.format("%Y-%m-%dT%H:%M:%SZ")); }
方法2:截断时间的毫秒部分
如果需要得到一个本身就不含毫秒的DateTime对象(而非仅格式化输出),可以调用trunc_subsecs(0)方法截断所有小数秒:
use chrono::Utc; fn main() { let current_time = Utc::now().trunc_subsecs(0); println!("{:?}", current_time); }
此时用{:?}打印就不会显示毫秒部分了。
内容的提问来源于stack exchange,提问作者GranBoh
相关产品推荐
相关产品推荐

