世界最大級のオンライン学習サービス「Udemy」のセール状況はこちら

【Flutter/Dart】DateTimeで現在時刻・日付を取得する

この記事はこんな人におすすめ!
  • Flutterで現在の時刻を取得したい
  • DateTimeで指定した単位(月, 日, 時, 分, etc)の値を取得したい

「Flutterで現在時刻・日付を取得するにはどうするの?」

今回はDateTimeを使用して現在時刻または日付を取得する方法を解説していきます。

目次

DateTimeで現在時刻・日付を取得する

現在時刻と日付を取得するにはDateTime.now()を使用します。

void main() {
  var now = DateTime.now();
  print(now);
}

//出力結果
//2023-11-12 15:25:57.609778

指定した年・月・日・時・分・秒を取得する

DateTimeから指定した単位の値を取得するには次のように書きます。

void main() {
  var now = DateTime.now();
  print(now);
  print(now.year);
  print(now.month);
  print(now.day);
  print(now.hour);
  print(now.minute);
  print(now.second);
}

//出力結果
//2023-11-12 15:25:57.609778
//2023
//11
//12
//15
//25
//57

参考サイト

目次