5
4

More than 3 years have passed since last update.

DartでString→DateTime型に変換

Last updated at Posted at 2020-09-16

経緯

FlutterでTextFormFieldに入れた日付をDateTime型で取りたかったのでメモ。

環境

$ flutter doctorDoctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.21.0-9.2.pre, on Linux, locale ja_JP.UTF-8)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.48.2)

こちらに書かれている通り、flutter_localizations(intl)の設定が必要です。
https://qiita.com/ko2ic/items/bd0d20d72c66e8231c5c

コード例

import "package:intl/intl.dart";

class Test {
  // "2020/09/16 22:16"みたいな文字列から取る場合
  static final _dateFormatter = DateFormat("y/M/d HH:mm");

  // String→DateTime変換
  DateTime getDatetime(String datetimeStr){
    Datetime result;

    // String→DateTime変換
    try {
      result = _dateFormatter.parseStrict(datetimeStr);

      // (補足)
      // parseStrict()を使うのが大事。
      // parse()だと存在しない日付がいい感じ(?)に計算されて変換された
      // 例)2020/9/32を入れた場合
      // _dateFormatter.parseStrict("2020/9/32"); // 結果→Exception
      // _dateFormatter.parse("2020/9/32"); // 結果→2020/10/2のDateTimeに変換

    } catch(e){
      // 変換に失敗した場合の処理
    }

    return result;
  }

}

所感

DateFormat.parse()って需要あるんかな…

参考

https://qiita.com/ko2ic/items/bd0d20d72c66e8231c5c
https://api.flutter.dev/flutter/intl/DateFormat-class.html

5
4
1

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
5
4