Home > OS >  Format DateTime in Flutter
Format DateTime in Flutter

Time:01-02

I'm building a chat app, so I want to format the DateTime just like any other messaging app, where it says "3 min ago", "Tuesday", "2 Hours ago", etc...

I have tried multiple packages but none of them worked.

CodePudding user response:

well you can simply create a function just for that and it's actually quite simple.

You can create a function that does that and example is below. You can probably modify below code to achieve what you need.

String displayDateDifferenceFromTodayWithMS(DateTime inputTime) {
  final d = inputTime;
  final now = DateTime.now();
  final diff = now.difference(d);
  final diffInYear = (diff.inDays / 365).floor();
  final diffInMonth = (diff.inDays / 30).floor();
  final diffInWeeks = (diff.inDays / 7).floor();
  if (diffInYear >= 1) {
    return '$diffInYear yr ago';
  } else if (diffInMonth >= 1) {
    return '$diffInMonth month ago';
  } else if (diffInWeeks >= 1) {
    return '$diffInWeeks week ago';
  } else if (diff.inDays >= 1) {
    return '${diff.inDays} days ago';
  } else if (diff.inHours >= 1) {
    return '${diff.inHours} hour ago';
  } else if (diff.inMinutes >= 1) {
    return '${diff.inMinutes} min ago';
  } else if (diff.inSeconds >= 3) {
    return '${diff.inSeconds} sec ago';
  } else {
    return 'now';
  }
}

CodePudding user response:

As others have commented, you should use the timeago package.

Using their example:

import 'package:timeago/timeago.dart' as timeago;

main() {
    final fifteenAgo = DateTime.now().subtract(Duration(minutes: 15));

    print(timeago.format(fifteenAgo)); // 15 minutes ago
    print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
    print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos
}

CodePudding user response:

use this code :

/// Turns a date into a formatted String. If the date is
///
/// * today it will return "Today"
/// * tomorrow it will return "Tomorrow"
/// * within 7 days from now it will return "x days from now"
/// * yesterday it will return "Yesterday"
/// * in the past it will return "x days ago".
String formatDate(DateTime date) {
  final int daysFromToday = differenceInDays(DateTime.now(), date);
  if (daysFromToday == 0) {
    return "Today";
  } else if (daysFromToday == 1) {
    return "Tomorrow";
  } else if (daysFromToday > 1 && daysFromToday <= 7) {
    return "$daysFromToday days from now";
  } else if (daysFromToday == -1) {
    return "Yesterday";
  } else if (daysFromToday < -1) {
    return "${-daysFromToday} days ago";
  }
  return DateFormat("dd.MM.yyyy").format(date.toLocal());
}

and this :

/// Turns a date into a formatted String with date and time. If the date is
/// today it will return "Today, HH:mm". If the date was yesterday, it will
/// return "Yesterday, HH:mm". If the date was before yesterday, it will return
/// "X days ago".
String formatDateAndTime(DateTime date) {
  final int daysFromToday = differenceInDays(DateTime.now(), date);
  if (daysFromToday == -1) {
    return "Yesterday, ${DateFormat("HH:mm").format(date.toLocal())}";
  } else if (daysFromToday == 0) {
    return "Today, ${DateFormat("HH:mm").format(date.toLocal())}";
  } else {
    return "${-daysFromToday} days ago";
  }
}

and you need this:

/// Returns the difference in days between [date1] and [date2]. The difference
/// is measured at midnight, i.e., how many "midnights" lie between [date1] and
/// [date2].
///
/// - E.g. 1: if [date1] is 2019-12-30 23:55:00.000 and [date2] is
/// 2019-12-31 00:05:00.000 the difference will be 1 (day).
///
/// - E.g. 2: if [date1] is 2019-12-30 00:05:00.000 and [date2] is
/// 2019-12-31 23:55:00.000 the difference will be 1 (day).
///
/// Make sure to pass both dates either in UTC or local time. If one is UTC and
/// the other is local this might lead to unexpected difference in days. E.g.
/// if the local time zone is UTC 2 and we pass in 2000-01-01 23:30:00.000 as
/// [date1] in local time and 2000-01-02 00:30:00.000 as [date2] in UTC we would
/// expect a difference in days of 1 but 0 is returned. In code:
///
/// ```
/// final date1 = DateTime.parse('2000-01-01 23:30:00.000');
/// final date2 = DateTime.parse('2000-01-02 00:30:00.000').toUtc();
/// final diff = differenceInDays(date1, date2); // <- returns 0, we expect 1
/// ```
int differenceInDays(DateTime date1, DateTime date2) {
  assert(
      date1.isUtc == date2.isUtc,
      'Comparing UTC and local dates leads to '
      'unpredictable difference in days.\n'
      'date1 (isUtc: ${date1.isUtc}) = $date1\n'
      'date2 (isUtc: ${date2.isUtc}) = $date2');
  date1 = _roundToDays(date1);
  date2 = _roundToDays(date2);
  return date2.difference(date1).inDays;
}

and :

/// Takes a date and returns a date at the beginning (midnight) of the same day.
///
/// Note that it matters whether the date is UTC or local. For example, assume
/// our time zone is UTC 2 (e.g. South Africa Standard Time) and our [date]
/// is 2000-01-01 01:00:00.000 (local time). If the [date] object is set to
/// local, then it will be rounded to 2000-01-01 00:00:00.000. However, if the
/// [date] object is set to UTC, it will be rounded to 1999-12-31 00:00:00.000Z.
DateTime _roundToDays(DateTime date) {
  final day = date.day;
  final month = date.month;
  final year = date.year;
  return date.isUtc
      ? DateTime.utc(year, month, day)
      : DateTime(year, month, day);
}
  • Related