formatDate function

String formatDate(
  1. String date, {
  2. bool showTime = false,
})

Formats a given date/time string into a user-friendly date representation.

This function takes a date/time string as input and formats it into a user-friendly date representation. It allows the option to show the time component by setting the showTime parameter to true. The function parses the input date string, and if parsing fails, it uses the current date as a fallback. The formatted date includes the day, month, year, and optionally the time component.

@param date The date/time string to format. @param showTime Whether to include the time component in the formatted date. @return A user-friendly formatted date string.

Implementation

String formatDate(String date, {bool showTime = false}) {
  final DateTime parsedDate =
      DateTime.tryParse(date)?.toLocal() ?? DateTime.now();
  final String postDayTime = DateFormat.jm().format(parsedDate);
  final String postDay = DateFormat.d().format(parsedDate);
  final String postMonth = DateFormat.MMMM().format(parsedDate);
  final String postYear = DateFormat.y().format(parsedDate);
  return '$postDay $postMonth, $postYear${showTime ? ' at $postDayTime' : ''}';
}