LoginSignup
3
0

More than 1 year has passed since last update.

【Rust】 日本時間の今日日付・0時0分0秒を取得する

Last updated at Posted at 2022-06-01

概要

Rustで日時を扱うの記事にある通り、Rustでは日時を扱うのに、chronoクレートを使用することが多いと思います。
今回はこのchronoクレートを使用して、日本時間の今日日付・0時0分0秒を取得してみたいと思います。

実装方針

  1. 概要欄で紹介した記事の、TimeZone有りの型から無しの型への変換、またはその逆の項にある通り、まずはUtc::now()でUTCの現在日時を取得します。後続の処理用にnaive_utcに変換しておきます。
  2. 上記の1で取得したnaive_utcchrono-tzのクレートを使用して、日本時間に変換します。How do I go from a NaiveDate to a specific TimeZone with Chrono?のstackoverflowの回答が参考になります。
  3. 最後に取得した日本時間の日時に、0時0分0秒を設定します。Rustの日付時刻処理(std::time, time, chrono)の「例: タイムゾーン指定で時刻を組み立てる (一意に決まる場合)」にある通り、and_hmsで全て0に設定すればいけそうです。

実装サンプル

use chrono::{DateTime, Datelike, TimeZone, Utc};
use chrono_tz::{Asia::Tokyo, Tz};

// 日本時間当日を0時0分0秒で返す
pub fn get_now_jst_date() -> DateTime<Tz> {
    let utc = Utc::now().naive_utc();
    let jst = Tokyo.from_utc_datetime(&utc);
    return Tokyo
        .ymd(jst.year(), jst.month(), jst.day())
        .and_hms(0, 0, 0);
}
3
0
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
0