timeFromNow static method

String timeFromNow(
  1. dynamic timeStamp, [
  2. dynamic bad = false
])

距离现在多久

Implementation

static String timeFromNow(timeStamp, [bad = false]) {
  int time = 0;

  if (timeStamp is int) {
    time = timeStamp;
  } else {
    time = int.parse(timeStamp.toString());
  }

  if (time < 13) {
    time = time * 1000;
  }

  var oldTime = DateTime.fromMillisecondsSinceEpoch(time);
  var nowTime = DateTime.now();

  var timeSting = '1秒前';

  if (oldTime.isBefore(nowTime)) {
    Duration duration = nowTime.difference(oldTime);
    int day = duration.inDays;
    int hour = duration.inHours.remainder(Duration.hoursPerDay);
    int minute = duration.inMinutes.remainder(Duration.minutesPerHour);
    int second = duration.inSeconds.remainder(Duration.secondsPerMinute);

    if (day > 7) {
      if (bad) {
        timeSting = '7天前';
      } else {
        timeSting = '${timeStampToString(timeStamp, 'yyyy-MM-dd HH:mm')}';
      }
    } else if (day > 1 && day <= 7) {
      timeSting = '$day天前';
    } else if (hour >= 1 && day <= 1) {
      timeSting = '$hour小时前';
    } else if (minute >= 1 && hour < 1) {
      timeSting = '$minute分前';
    } else if (second > 0 && minute < 1) {
      timeSting = '$second秒前';
    }
  }

  return timeSting;
}