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: