Flutter provides the intl package for formatting dates, which is part of the Flutter SDK. You can import it into your project using the following code:

import 'package:intl/intl.dart';

Once you have the intl package imported, you can use the DateFormat class to format dates in different ways. Here are some examples:

  • Formatting a date as a string with the default locale:
DateTime date = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd').format(date);
print(formattedDate); // Output: 2023-02-21
  • Formatting a date as a string with a specific locale:
DateTime date = DateTime.now();
String formattedDate = DateFormat('EEEE, MMMM d, y', 'en_US').format(date);
print(formattedDate); // Output: Monday, February 21, 2023
  • Formatting a date as a string with a custom pattern:
DateTime date = DateTime.now();
String formattedDate = DateFormat('MM/dd/yyyy HH:mm:ss').format(date);
print(formattedDate); // Output: 02/21/2023 16:34:25
  • Parsing a date string into a DateTime object:
String dateString = '2023-02-21';
DateTime date = DateFormat('yyyy-MM-dd').parse(dateString);
print(date); // Output: 2023-02-21 00:00:00.000

These are just a few examples of how to format dates in Flutter using the intl package. There are many more options available, such as formatting times, using custom date symbols, and more. You can find more information on the intl package and its capabilities in the Flutter documentation.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *