Top 7 Date methods you should know (Dart)
Learn how to work with dates in Dart

In this tutorial, we will look at the Top 7 methods to make you productive when working with dates in Dart. Using dates come in the form of the DateTime
class, which proves effective when implementing features for interfaces like calendars, schedules and appointments.
Here is an example snippet showing how to create a DateTime
object in Dart:
var now = DateTime.now();
var berlinWallFell = DateTime.utc(1989, 11, 9);
var moonLanding = DateTime.parse("1969-07-20 20:18:04Z");
You can retrieve useful information like so:
berlinWallFell.year; // => 1989
berlinWallFell.month; // => 11 (November) numbering starts from 1 (January)
berlinWallFell.day; // => 9
berlinWallFell.weekday; // => 4 (Thursday) numbering starts from 1 (Monday)
If you like what you see so far then read on!
1. add()
This adds the provided duration and returns a new DateTime
instance:
var berlinWallAdd10 = berlinWallFell.add(Duration(days: 10, hours: 5))); // 19th of November at 05:00 hrs
print(berlinWallAdd10.day); // => 19
print(berlinWallAdd10.hour); // => 5
2. difference()
This accepts another DateTime
object, returning the difference as a Duration
object. You can then extract the days, hours, minutes and so on.
var diff = berlinWallFell.difference(moonLanding);
diff.inDays; // => 7416 - log these out with print(diff.inDays);
diff.inHours; // => 177987
diff.inMinutes; // => 10679261
3. isAfter(DateTime other)
This checks that the given date is after other
:
moonLanding.isAfter(berlinWallFell); // => false
4. isBefore(DateTime other)
This checks that the given date is before other
:
moonLanding.isBefore(berlinWallFell); // => true
5. compareTo(DateTime other)
Checks to see that the date values are equal. Returns 0
if they are.
berlinWallFell.compareTo(berlinWallFell); // => 0 (equal)
moonLanding.compareTo(berlinWallFell); // => -1 (not equal)
6. subtract(Duration duration)
Subtracts the given duration from the date.
berlinWallFell.subtract(
Duration(days: 7416, hours: 3, minutes: 41, seconds: 56)); // => 1969-07-20 20:18:04.000Z (about the day and time of the moon landing)
7. toLocal()
Returns the date in the local time zone. Useful for i18n.
moonLanding.toLocal(); // => 1969-07-20 21:18:04.000
And a bonus… 🥁
8. toUtc()
Returns the date in UTC time.
moonLanding.toUtc(); // => 1969-07-20 20:18:04.000Z
moonLanding.timeZoneName; // => UTC
Conclusion
I hope this was insightful and if this is your first exposure to Dart, read my first steps tutorial to grasp the basics. The code snippets for this article are available on DartPad.
Like and follow me 😍 for more articles on Dart.
Further reading
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.