YouTube Description:

Learn built in date options you can use with Flutter including adding and subtracting from dates, getting the difference between two dates, checking if a date is before or after another date, and some minor formatting you can do without additional plugins.

At some point when you're building apps using Flutter you're more than likely going to need to work with Dates. And working with Dates can be somewhat frustrating and confusing. So here's a little introduction on working with Dates that will get you started.

 

The first thing we will learn is how to get the current date and time, by using now. Clear out Everything in main.dart, enter this and hit run:

void main() { print(DateTime.now()); }

And you will see in the debug console the current date:

flutter: 2021-09-29 15:55:57.975526

And you can set a specific date by using parse like this:

void main() { print(DateTime.parse("2021-09-29 15:15")); }

This will, of course, produce this:

flutter: 2021-09-29 15:15:00.000
 

To get the difference between two dates you can use... you guessed it... difference. So let's set up a few variables to play with:

DateTime date1 = DateTime.parse("2021-01-01 00:00:00"); DateTime date2 = DateTime.parse("2021-01-01 05:00:00");

So our first date is midnight and our second date is 5am the same day. We can now get the difference in minutes:

print(date2.difference(date1).inMinutes);

flutter: 300

and hours:

print(date2.difference(date1).inHours);

flutter: 5

You have a few options for getting the difference in the dates:

 

Now you will notice if you set the dates say, like so:

DateTime date1 = DateTime.parse("2021-01-01 05:00:00"); DateTime date2 = DateTime.parse("2021-01-02 00:30:00");

And you try to get the difference in Days:

print(date2.difference(date1).inDays);

The result will be 0 days:

flutter: 0

It's because even though your second date IS the next day, it hasn't been a full 24 hours so it is saying 0 days. You can resolve that by either dividing the minutes by 24 hours and rounding up:

print((date2.difference(date1).inHours / 24).round());

flutter: 1

Or ideally probably just remove the times:

DateTime date1 = DateTime.parse("2021-01-01"); DateTime date2 = DateTime.parse("2021-01-02");

flutter: 1

Or you *could* just get the hours and minutes by doing this:

int hours = date2.difference(date1).inHours; int minutes = (date2.difference(date1).inMinutes % 60); print('$hours hours and $minutes minutes');

flutter: 19 hours and 30 minutes

The % is a modulo operator and provides you with the remainder when dividing.

 

We can also add to or subtract from a date. If we take this date here:

DateTime date1 = DateTime.parse("2021-01-01 12:00:00");

We can add 6 hours to it by doing this:

print(date1.add(const Duration(hours: 6)));

flutter: 2021-01-01 18:00:00.000

Or subtract 6 hours by using subtract:

print(date1.subtract(const Duration(hours: 6)));

flutter: 2021-01-01 06:00:00.000

And again you have multiple options for duration:

 

You can also see if a date is before or after another date. Using these two dates here:

DateTime date1 = DateTime.parse("2021-01-01 00:00:00"); DateTime date2 = DateTime.parse("2021-01-02 00:00:00");

We can run this:

print(date1.isBefore(date2));

Will produce true:

flutter: true

And in relation, isAfter:

print(date1.isAfter(date2));

Will produce false.

flutter: false
 

So everything so far has technically been Dart, which is the programming language Flutter runs on.

So let's actually do some date stuff inside a flutter app. We will start with our tutorial boilerplate:

import 'package:flutter/material.dart'; void main() => runApp(const DateApp()); class DateApp extends StatefulWidget { const DateApp({Key? key}) : super(key: key); @override _DateAppState createState() => _DateAppState(); } class _DateAppState extends State<DateApp> { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text("Let's work with Dates!")), ), ); } }

Keep in mind this is just a simplified boilerplate used for this tutorial and shouldn't be used as a reference for proper app structure.

 

Now let's add a form with two text fields and a submit button:

home: Scaffold( appBar: AppBar(title: const Text("Let's work with Dates!")), body: Form( child: Column( children: [ TextFormField(), TextFormField(), ElevatedButton( onPressed: () {}, child: const Text('calculate'), ), // ElevatedButton ], ), // Column ), // Form ), // Scaffold

 

Ok now let's set up three variables; two for the dates and one for the result:

class _DateAppState extends State<DateApp> { DateTime date1 = DateTime.parse("2021-01-01 00:00:00"); DateTime date2 = DateTime.parse("2021-01-01 06:00:00"); String result = 'No results yet.'; @override

Now we will add the result to the appBar:

home: Scaffold( appBar: AppBar(title: Text(result)), body: Column(

And then let's go ahead and set the default values of the text fields to the values of our two date variables:

children: [ TextFormField( initialValue: date1.toString(), ), //TextFormField TextFormField( initialValue: date2.toString(), ), //TextFormField ElevatedButton(

 

Now let's get some results! Let's first set up a global key so we can access the form field values when we press the calculate button:

String result = 'No results yet.'; final GlobalKey<FormState> _key = GlobalKey<FormState>(); @override

And then we need to set the key in the form like so:

body: Form( key: _key, child: Column(

Now we need to add the onSaved calls to the textFields that set the two date variables:

children: [ TextFormField( initialValue: date1.toString(), onSaved: (String? fieldValue) { date1 = DateTime.parse(fieldValue!); }), // TextFormField TextFormField( initialValue: date2.toString(), onSaved: (String? fieldValue) { date2 = DateTime.parse(fieldValue!); }), // TextFormField ElevatedButton(

Note: The ! on "fieldValue!" is saying we guarantee that the fieldValue will not be null. We are just setting it this way for this tutorial. In a real scenario you would want to error trap for null before doing these calculations.

And then in the ElevatedButton we will add this code:

ElevatedButton( onPressed: () { _key.currentState!.save(); setState(() { int hours = date2.difference(date1).inHours; int minutes = (date2.difference(date1).inMinutes % 60); result = '$hours hours and $minutes minutes'; }); }, child: const Text('calculate'), ), // ElevatedButton

We won't be doing any validation since we are just wanting to do date calculations, but you will normally want to validate your form before saving.

So this saves the field values and then displays the difference in hours between the two dates in the AppBar:

 

Now you CAN do some minimalistic formatting without adding any extra dependencies to your app. Here we will take the first date, add 60 days to it, and then format the date to be month/day/year hour:minute.

setState(() { DateTime plusSixty = date1.add(const Duration(days: 60)); result = plusSixty.month.toString().padLeft(2, '0') + '/' + plusSixty.day.toString().padLeft(2, '0') + '/' + plusSixty.year.toString() + ' ' + plusSixty.hour.toString().padLeft(2, '0') + ':' + plusSixty.minute.toString().padLeft(2, '0'); });

So this gets the job done as you see here:

But if you want advanced date formatting it's best to use a date formatting package... Which we will get into in another video!

 

Click here for the source code. This is actually before the date formatting.

 

More Videos