Skip to content

Formatting Dates/Times with Flutter and intl

Flutter, Dart, intl, format1 min read

Today I thought I'd write a quick post on formatting dates and times to human-readable strings in Flutter. All of this can be done pretty simply with the intl dart package. The intl package does a lot of other thing as well, and has pretty long and robust documentation so I'm only going to be focusing on formatting dates/times in this post.

Anyway, back to the task at hand. If you have a point in time in milliseconds(since epoch) and you want to convert it into a human-readable format first you have to import the intl package(remember to install it first in your pubspec.yaml file):

1import 'package:intl/intl.dart';

Then you have to create a DateFormat object with the template that you're going to use:

1final template = DateFormat('yyyy-MM-dd');

The above example will convert the milliseconds value to a date in time(ex. 2019-09-08). The above example is not exhaustive so if you want to display the hour of the day or minutes etc. you can do so. Here's some other examples taken from the documentation:

1Format Pattern Result
2-------------- -------
3'yyyy.MM.dd G 'at' HH:mm:ss vvvv' 1996.07.10 AD at 15:08:56 Pacific Time
4'EEE, MMM d, ''yy' Wed, Jul 10, '96
5'h:mm a' 12:08 PM
6'hh 'o''clock' a, zzzz' 12 o'clock PM, Pacific Daylight Time
7'K:mm a, vvv' 0:00 PM, PT
8'yyyyy.MMMMM.dd GGG hh:mm aaa' 01996.July.10 AD 12:08 PM

After you've created the DateFormat object above you just need to call the format function and pass a DateTime object and it will return the readable string to you. In the case explained above you would have a raw milliseconds value so it would look something like this:

1final label = template.format(DateTime.fromMillisecondsSinceEpoch(milliseconds));

And here's a full example of everything combined above into a method:

1String formatDate(int milliseconds) {
2 final template = DateFormat('yyyy-MM-dd');
3 return template.format(DateTime.fromMillisecondsSinceEpoch(milliseconds));

If you pass the milliseconds to formatDate it will return a human-readable date string.