Skip to content
DeveloperMemos

Formatting a Date in Flutter/Dart

Flutter, Dart, Flutter Tips1 min read

If you're making an app that has posts or needs to display a time for some reason you're probably going to need to format a Date object into a readable format. This is a quick post about how to format a DateTime object into a readable String in Dart/Flutter.

So, first of all Flutter has a class called DateTime, you can create an instance of this for right now using DateTime.now(). If you're working with milliseconds you can use DateTime.fromMillisecondsSinceEpoch instead. To format the DateTime object into a readable String you need to make use of the intl package. You can read more about the package here if you want to. If you don't just make sure you add the dependency to your pubspec.yaml:

1dependencies:
2 intl: ^0.16.1

After this you can use the DateFormat class, use this to create a formatter like this:

1final DateFormat formatter = DateFormat('yyyy/MM/dd');

And then you call the format method and pass the DateTime object to it:

1final String dateString = formatter.format(now);

Here's what the output looks like:

2021/01/28

Here's a full example:

1final DateTime now = DateTime.now();
2final DateFormat formatter = DateFormat('yyyy/MM/dd');
3final String dateString = formatter.format(now);

It's probably worth mentioning that DateFormat has a few handy methods, like DateFormat.yMd() which will give a similar result as above. There's also a chart in the docs that shows different patterns/combinations that can be used, you can find it here.