getDateDiffAsString static method

String getDateDiffAsString(
  1. DateTime previousTime, {
  2. DateTime? currentDate,
  3. String dateFormat = FORMAT_EEE_MMM_d_yyy,
})

Implementation

static String getDateDiffAsString(DateTime previousTime, {DateTime? currentDate, String dateFormat = FORMAT_EEE_MMM_d_yyy}){
  final targetDate = currentDate ?? DateTime.now();
  final dateDiff = targetDate.difference(previousTime);

  final day = dateDiff.inDays < 0 ? dateDiff.inDays*-1 : dateDiff.inDays;

  if(day > 31){
//      if(day > 365){
      return dateToString(previousTime, format: FORMAT_d_MMM_yyyy);
//      }
//      return dateToString(previousTime, format: FORMAT_d_MMM);
  }

  if(day > 0){
    if(day.toInt() == 1) {
      return "${day.toInt()} day ago";
    }
    if(day.toInt() > 6){
      return dateToString(previousTime, format: dateFormat);
    }
    return "${day.toInt()} days ago";
  }

  final hour = dateDiff.inHours < 0 ? dateDiff.inHours*-1 : dateDiff.inHours;
  if(hour > 0){
    if(hour.toInt() == 1){
      return "1 hr ago";
    }
    return "${hour.toInt()} hrs ago";
  }

  final minute = dateDiff.inMinutes < 0 ? dateDiff.inMinutes*-1 : dateDiff.inMinutes;
  if(minute > 0){
    if(minute.toInt() == 1){
      return "1 min ago";
    }
    return "${minute.toInt()} mins ago";
  }

  final second = dateDiff.inSeconds < 0 ? dateDiff.inSeconds*-1 : dateDiff.inSeconds;
  if(second.toInt() < 1){
    return "Just now";
  }
  if(second.toInt() == 1){
    return "1 sec ago";
  }
  return "${second.toInt()} secs ago";
}