LoginSignup
2
0

More than 1 year has passed since last update.

Flutterで「2022-01-01 00:00:00」の日付文字列を「●日前」、「●分前」に変換する

Last updated at Posted at 2022-03-24

やりたいこと

"2022-03-20 12:33:55"
↓
"35分前"

「文字列日時」を「●日前・時間前・分前」に変換する

下準備

intlが必要なので、まずintlをpub addしましょう

$ flutter pub add intl
$ flutter pub get

方法

import 'package:intl/intl.dart';  // 先ほどのintlを読み込む

// 変換用の関数を作る
String convertFromNowString(String dateStr) {
  DateFormat dateFormatter = DateFormat("y-M-d HH:mm:ss");
  DateTime dateTime = dateFormatter.parseStrict(dateStr);

  final Duration difference = DateTime.now().difference(dateTime);
  final int sec = difference.inSeconds;

  if (sec >= 60 * 60 * 24) {
    return '${difference.inDays.toString()}日前';
  } else if (sec >= 60 * 60) {
    return '${difference.inHours.toString()}時間前';
  } else if (sec >= 60) {
    return '${difference.inMinutes.toString()}分前';
  } else {
    return '$sec秒前';
  }
}

// いざ処理
String timeStr = convertFromNowString("2022-03-20 12:33:55");
// これで timeStr = "35分前(現在時刻との差異時間)" になっています!

以上です。

convertFromNowStringの関数については下記記事からコピペさせていただきました。

@seiboy さん、ありがとうございます。

2
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
2
0