rust 将时间转换为时间戳时,默认输入时间是utc格式,需要调用Local模块才能处理时区。
fn get_timestamp(date_str: &String) -> i64 {
let naive_date_time = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S");
match naive_date_time {
Ok(naive_date_time) => {
let parsed = Local.from_local_datetime(&naive_date_time).single();
match parsed {
Some(parsed) => {
println!("parsed:{}", parsed);
parsed.timestamp()
}
None => 0,
}
}
Err(err) => {
println!("err:{}", err);
0
}
}
}
调用测试
use chrono::{DateTime, Local, TimeZone};
fn main() {
let dt1: DateTime<Local> = Local::now();
let dt2 = dt1.timestamp();
println!("dt1:{} dt2:{}", dt1, dt2);
let date_str = "2023-12-08 14:51:49";
let tamp = get_timestamp(&date_str.to_string());
println!("tamp:{}", tamp);
}