I need to display the Day of the Week, Month and Number of Day in Text in Flutter like so : "Today is Monday February 4th". I tried using the dart package intl but its not working.

import 'package:intl/intl.dart';


Solution 1: Amit Jangid

To format date you are using the right package. You just have to pass the correct date format to get the desired result.

Check the flutter docs for DateFormat class

An Example for this would be:

var _formattedDate = DateFormat('EEEE MMMM dd').format(DateTime.now());
print(_formattedDate);

The result for above code is: Thursday February 07

If you want to add the suffix as well, then you can try this..

if (_formattedDate.endsWith('1')) {
  _formattedDate += 'st';
} else if (_formattedDate.endsWith('2')) {
  _formattedDate += 'nd';
} else if (_formattedDate.endsWith('3')) {
  _formattedDate += 'rd';
} else {
  _formattedDate += 'th';
}

print(_formattedDate);

The result for above code is: Thursday February 07th


Solution 2: ibhavikmakwana

@AmitJangid has an answer for you, But there is no inbuilt function to add the suffix.

You can add it using below code:

formatDate() {
  var date = DateTime.now();
  var suffix = "th";
  var digit = DateTime.now().day % 10;
  if ((digit > 0 && digit < 4) && (date.day < 11 || date.day > 13)) {
    suffix = ["st", "nd", "rd"][digit - 1];
  }
  return DateFormat("EEEE MMMM d'$suffix'").format(DateTime.now());
}

In your Text Widget,

Text(
  "Today is " + formatDate(),
),

You will get:

Today is Thursday February 7th