getDateTimeDiffAsString static method

String getDateTimeDiffAsString(
  1. DateTime previousTime, {
  2. DateTime? currentDate,
})

Implementation

static String getDateTimeDiffAsString(DateTime previousTime, {DateTime? currentDate}){
  final targetDate = currentDate == null ? DateTime.now() : currentDate;
  final dateDiff = targetDate.difference(previousTime);

  final day = dateDiff.inDays < 0 ? dateDiff.inDays*-1 : dateDiff.inDays;
  if(day > 0){
    if(day.toInt() == 1) {
      return "1 day ago at ${dateToString(previousTime, format: FORMAT_hh_mm_a)}";
    }
    if(day.toInt() > 6){
     return "${dateToString(previousTime, format: FORMAT_EEE_MMM_d_yyy)}, ${dateToString(previousTime, format: FORMAT_hh_mm_a)}";
    }
    return "${day.toInt()} days ago at ${dateToString(previousTime, format: FORMAT_hh_mm_a)}";
  }

  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";
}