Top 7 Date methods you should know

Top 7 Date methods you should know

In this tutorial, we will look at the Top 7 methods to make you productive when working with dates. 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)

DateTime comes with some useful constant values for days and months:

moonLanding.weekday == DateTime.sunday; // => true
moonLanding.month == DateTime.july; // => true
DateTime.daysPerWeek; // => 7

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 are then able to extract the days, hours, minutes and so on.

var diff = berlinWallFell.difference(moonLanding);

print(diff.inDays); // => 7416
print(diff.inHours); // => 177987
print(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 equal.

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, share and follow me for more articles on Dart.

  1. DateTime class Documentation

  2. Duration class Documentation

  3. Free Dart screencasts on Egghead.io