0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustのchronoクレートの文字列からdate型に変換

Posted at

文字列から日付のみ型(NativeDate)に変換する際の注意点

Chronoを使用して日付を処理する際、文字列から日付型変換する時にハマってしまったので、自分用の備忘録としてまとめます。

結論

yyyy-mm-dd形式の文字列から日付のみの型に変換したい場合、NaiveDateTimeではなく、NaiveDateを使用する必要があります。NaiveDateTimeはエラーとなり、NaiveDateを使わないといけません。

問題の背景

Chronoライブラリを使うとき、DateTime型に変換しようとすることがありますが、日付だけを扱いたい場合は、DateTimeではなく、NaiveDateを使う必要があります。特に、NaiveDateタイムゾーン情報を持たない日付のみを扱います。

エラー例

use chrono::NaiveDateTime;

fn main() {
    let date_str = "2025-03-29";
    let date = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d");
    
    match date {
        Ok(d) => println!("Parsed date: {}", d),
        Err(e) => println!("Error: {}", e),
    }
}

上記のコードでは、"2025-03-29"という文字列をNaiveDateTime型に変換しようとしています。しかし、NaiveDateTime型は日付と時刻の両方を含むため、時刻情報が不足している場合にエラーが発生します。

注意点

  • NaiveDateTimeでは、時刻も含まれるため、日付のみに変換したい場合はNaiveDateを使うことが必須です。
  • NaiveDateはタイムゾーン情報を持たないため、日付のみを扱いたい場合には非常に便利です。

正しい使い方

use chrono::NaiveDate;

fn main() {
    let date_str = "2025-03-29";
    let date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d");

    match date {
        Ok(d) => println!("Parsed date: {}", d),
        Err(e) => println!("Error: {}", e),
    }
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?