loading...
Cover image for Top 7 Date methods you should know (Dart)

Top 7 Date methods you should know (Dart)

graphicbeacon profile image Jermaine Oppong Updated on ใƒป2 min read

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 and follow me ๐Ÿ˜ for more articles on Dart.

Quicklinks

  1. DateTime class Documentation
  2. Duration class Documentation
  3. Free Dart screencasts on Egghead.io

Posted on by:

graphicbeacon profile

Jermaine Oppong

@graphicbeacon

Web Developer | Google Dart enthusiast | Egghead.io instructor | YouTuber ๐Ÿ“น | Read my blog โœ๐Ÿพ https://www.creativebracket.com

Discussion

pic
Editor guide
 

For those who don't want to hard-code the Date as "$September 15, 2018" or "12:00AM". you can use intl from pub.dartlang.org

At first I did the hard-code of displaying the date & time in a proper format. then I realized that there's also a package that made it easy to code it.

 

This is a pretty solid representing of Dart. I feel like you can know a lot from how a language treats dates.

 

Pleased to see that Dart is quite sane in its API and dates/times carry around the time zone.

I still get frustrated because after many years I still have to deal with date times without a timezone in Python. From the standard library:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 9, 15, 1, 51, 58, 769069)
>>> datetime.datetime.utcnow()
datetime.datetime(2018, 9, 14, 23, 52, 4, 568886)
>>> datetime.datetime.now().isoformat()
'2018-09-15T01:52:14.024139'
>>> datetime.datetime.utcnow().isoformat()
'2018-09-14T23:52:23.090149'

Neither the local time, now(), nor the UTC time carry the time zone so if you pass that around you're bound to mess it up, they call those "naive datetimes" vs "time zone aware datetimes" but I call them "useless datetimes" :D

No wonder Python has so many datetime libraries (each word links to a different library :D)

 

Great article!

For those who don't know there is MomentJS for JavaScript that implements all these methods.

 

Thanks Sergiu. I grant that MomentJS implements some useful util methods for dates.

However the beauty here is that all these methods come inbuilt with Dart, so no extra dependencies needed.