Working with Dates in Dart

Darshan Kawar
Flutter Community
Published in
5 min readApr 4, 2020

--

Photo by Panos Sakalakis on Unsplash

Dates are a common type of data mostly coming back from api response that is consumed by many apps.

The end users of the app are only concerned about the date displayed in a meaningful and readable format, which will help them to understand the data better, and not get confused with it.

In this article, we’ll take a look at below two Date specific classes and their methods that help to properly parse and format the date which then can be further used to display in the UI:

  • DateTime
  • DateFormat

DateTime

This class exposes below methods that are used to work upon the DateTime objects:

  • now():

Simplest method that returns current date and time.

print(DateTime.now()); // 2020–04–02 13:49:46.635

Once we get the current date, we can also retrieve individual units of the date, ie month, year, day, seconds, hour , minute and so on, as shown below:

var currDt = DateTime.now();
print(currDt.year); // 4
print(currDt.weekday); // 4
print(currDt.month); // 4
print(currDt.day); // 2
print(currDt.hour); // 15
print(currDt.minute); // 21
print(currDt.second); // 49
  • add():

This method accepts the duration in the form of days, hours, minutes, seconds and so on and returns the updated date.

var addDt = DateTime.now();
print(addDt.add(Duration(days: 5, hours: 5, minutes: 30))); //2020–04–07 21:02:09.367
  • isAfter():

This method returns a bool after checking both dates.

var anotherDt = DateTime.now().subtract(Duration(days: 10, hours: 10));
print(addDt.isAfter(anotherDt)); // true

Notice that I used subtract method which removes the given duration from the date.

Similarly, there’s .isBefore() method which also returns a bool after checking both dates.

var subDt = DateTime.now().subtract(Duration(days: 10, hours: 10));
print(addDt.isBefore(subDt)); // true
  • difference():

This method returns the difference between two provided dates which in turn can be used to extract individual units of the resulting date.

var diffDt = addDt.difference(subDt); // 249:59:59.999000
print(diffDt.inSeconds);
print(diffDt.inHours);
print(diffDt.inMinutes);
print(diffDt.inDays);
  • isAtSameMomentAs():

This method usually is used to compare two DateTime objects and returns a bool.

print(addDt.isAtSameMomentAs(anotherDt)); // false

There’s a similar method named compareTo() which works on same line as isAtSameMomentAs(), with only difference is, it returns an int instead of bool

print(addDt.compareTo(anotherDt)); // 1

  • toUtc():

This method converts a given date into UTC (Universal Time Coordinated). Before converting into UTC, we can check if the given date is in UTC format already, by using isUtc which returns a bool. If it returns false then we can go ahead and convert the same date into UTC.

print(addDt.isUtc); // false
print(addDt.toUtc()); // 2020–04–02 13:33:29.971Z

Similar to utc, we can also get the current timeZone and it’s offset from the timeZone as below:

print(addDt.timeZoneName); // India Standard Time
print(addDt.timeZoneOffset); // 5:30:00.000000

  • parse():

Most of the time, the date from api response is in String that we need to convert into DateTime object. This we can achieve using parse() method which takes string as an argument, as below:

String strDt = "1984–04–02";
DateTime parseDt = DateTime.parse(strDt);
print(parseDt); // 1984–04–02 00:00:00.000

Extracting / parsing date in specific format

DateFormat is used to convert / parse dates into specific format (ex : yyyy-MM-d, yy-MM-dd). In order to use this class, we need to add intl as a dependency in pubspec.yaml and then import the package in the dart file.

With this class, we can convert / format DateTime instance into String format and furthermore, we can also specify the type of format in which we want to display the date. Let’s see an example:

Let’s first create an instance of DateTime object as:

var dt = DateTime.now();

Then we’ll create an instance of DateFormat and pass the format we want and then use .format method and pass the date we want to format.

var newFormat = DateFormat("yy-MM-dd");
String updatedDt = newFormat.format(dt);
print(updatedDt); // 20-04-03

There are many other options to format the date. Some of them are:

 DAY                          d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
STANDALONE_MONTH LLLL
NUM_MONTH M
NUM_MONTH_DAY Md
NUM_MONTH_WEEKDAY_DAY MEd
ABBR_MONTH MMM
ABBR_MONTH_DAY MMMd
ABBR_MONTH_WEEKDAY_DAY MMMEd
MONTH MMMM
MONTH_DAY MMMMd
MONTH_WEEKDAY_DAY MMMMEEEEd
ABBR_QUARTER QQQ
QUARTER QQQQ
YEAR y
YEAR_NUM_MONTH yM
YEAR_NUM_MONTH_DAY yMd
YEAR_NUM_MONTH_WEEKDAY_DAY yMEd
YEAR_ABBR_MONTH yMMM
YEAR_ABBR_MONTH_DAY yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY yMMMEd
YEAR_MONTH yMMMM
YEAR_MONTH_DAY yMMMMd
YEAR_MONTH_WEEKDAY_DAY yMMMMEEEEd
YEAR_ABBR_QUARTER yQQQ
YEAR_QUARTER yQQQQ
HOUR24 H
HOUR24_MINUTE Hm
HOUR24_MINUTE_SECOND Hms
HOUR j
HOUR_MINUTE jm
HOUR_MINUTE_SECOND jms
HOUR_MINUTE_GENERIC_TZ jmv
HOUR_MINUTE_TZ jmz
HOUR_GENERIC_TZ jv
HOUR_TZ jz
MINUTE m
MINUTE_SECOND ms
SECOND s

Let’s take a look at an example by converting a date into YEAR_ABBR_MONTH_WEEKDAY_DAY for which the shorthand we need to use is yMMMEd

var newDt = DateFormat.yMMMEd().format(dt);
print(newDt); // Fri, Apr 3, 2020

As a conclusion, the classes we saw above and their methods can be used to tackle different types of dates coming back from api response.

For further reading on these classes:

https://api.dart.dev/stable/2.7.2/dart-core/DateTime-class.html

Thanks for reading and feel free to comment below your thoughts or any suggestions/feedback on this article.

I am available on Twitter, LinkedIn, and Github.

My other articles on Flutter are:

--

--

Darshan Kawar
Flutter Community

Open Source Support Engineer For Flutter @nevercodeHQ. Android Nanodegree Certified. Previously, Android Automation Test Engineer.