3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ユニークビジョン株式会社Advent Calendar 2019

Day 21

Rustでchronoを使ってTwitterAPIが返す日付を変換する

Posted at

目的

TwitterAPIを叩くと以下のような日付が返ってきます。

{
"created_at": "Thu Apr 06 15:28:43 +0000 2017"
}

この値をchronoのDateTime<Utc>に変換したいです。当初ただparse()を呼べばよいのかと思ったら、きちんとフォーマットを指定して変換しないとダメなことがわかりました。
serde_json::Valueとjsonのキーを渡して、日付を返すメソッドを作成しました。ここではパースに失敗した場合Utc.timestamp(0, 0)を返しています。

プログラム

Cargo.toml
[package]
name = "json"
version = "0.1.0"
edition = "2018"

[dependencies]
serde_json = "*"
chrono = "*"
main.rs
#[macro_use]
extern crate serde_json;
use chrono::prelude::*;
fn main() {
    let p = json!({
        "created_at": "Thu Apr 06 15:28:43 +0000 2017"
    });
    let t = get_date_time_from_json(&p, "created_at");
    println!("{}", t);
}

fn get_date_time_from_json(src: &serde_json::Value, key: &str) -> DateTime<Utc> {
    match src[key].as_str() {
        Some(timestamp) => {
            Utc.datetime_from_str(timestamp, "%a %b %d %T %z %Y")
                .unwrap_or(timestamp.parse().unwrap_or(Utc.timestamp(0, 0)))
        }
        None => Utc.timestamp(0, 0),
    }
}
2017-04-06 15:28:43 UTC
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?