How to format DateTime in Flutter

CodeWithFlutter
1 Min Read

You can use the DateFormat class from the intl package in Flutter to format DateTime objects. Here’s an example of how you can use it:

import 'package:intl/intl.dart';

void main() {
  DateTime now = DateTime.now();
  String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
  print(formattedDate);
}

In this example, now is a DateTime object that represents the current time. We use the format method of the DateFormat class to format the DateTime object into a string using the specified pattern (yyyy-MM-dd – kk:mm in this case). The resulting string is then stored in the formattedDate variable.

You can specify any pattern that you like by using the format codes. For example, yyyy stands for the year, MM stands for the month, dd stands for the day, kk stands for the hour (24-hour format), and mm stands for the minute.

Share this Article
Leave a comment