Rust with_timezoneを使って日時をUTCに変換する方法

環境
Windows 10 Home 64bit
rustc 1.66.0

構文
let 変数名: DateTime<Local> = Local.datetime_from_str(“日付", “日付の形式").unwrap();
変数名.with_timezone(&Utc);
日時をUTCに変換するは、「chrono」の「with_timezone」を使用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
use chrono::{DateTime, Local, Utc, TimeZone};
fn main() {
let date1: DateTime<Local> = Local.datetime_from_str("2023/01/31 11:22:33", "%Y/%m/%d %H:%M:%S").unwrap();
let res: DateTime<Utc> = date1.with_timezone(&Utc);
println!("date1: {}", date1);
println!("result: {}", res);
}
use chrono::{DateTime, Local, Utc, TimeZone}; fn main() { let date1: DateTime<Local> = Local.datetime_from_str("2023/01/31 11:22:33", "%Y/%m/%d %H:%M:%S").unwrap(); let res: DateTime<Utc> = date1.with_timezone(&Utc); println!("date1: {}", date1); println!("result: {}", res); }
use chrono::{DateTime, Local, Utc, TimeZone};

fn main() {

    let date1: DateTime<Local> = Local.datetime_from_str("2023/01/31 11:22:33", "%Y/%m/%d %H:%M:%S").unwrap();
    
    let res: DateTime<Utc> = date1.with_timezone(&Utc);

    println!("date1: {}", date1);
    println!("result: {}", res);

}

実行結果
date1: 2023-01-31 11:22:33 +00:00
result: 2023-01-31 11:22:33 UTC

Rust

Posted by arkgame