Flutter: How to Format DateTime with Example Code [intl Package]

Today, you will learn how to format DateTime in a flutter.

For, just creating a date-time object that shows the current date and time to the app screen we use DateTime.now().

We use the intl package by going to the "pub.dev" and searching the intl.

searching intl in pub dev

Click the first result

intl package page will be shown.

pub.dev intl package install folder

Go to the install section

Move down and copy the code below dependencies.

intl: ^0.17.0

This is the current intl version, you should copy the latest one.

Go Back to your and create a sample app.

Create a custom home screen with Scaffold, Center, and Text widget.

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Text(
      'Hello',
        style: const TextStyle(fontSize: 24),
      )),
    );
  }
}

Now, Create the show the current date inside the Text() Widget by using

DateTime.now()

but Text() widget take the string as an argument so make sure you use .toString() after DateTime.now().

snippet

DateTime.now().toString()

Now save the project with this code

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Text(
        DateTime.now().toString(),
        style: const TextStyle(fontSize: 24),
      )),
    );
  }
}

The current date will be shown on the screen. Now let’s format the date using our intl package

For that purpose we use the DateFormat class from the intl and this DateFormat will take the string pattern ('yyyy-MM-dd KK:mm:ss a') which we use to formate the date. Look at the snippet

DateFormat('yyyy-MM-dd KK:mm:ss a').format(DateTime.now())

Here, .format() will take the DateTime object which we pass an argument and which we want to format.

Lets see the final code

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Text(
        DateFormat('yyyy-MM-dd KK:mm:ss a').format(DateTime.now()),
        style: const TextStyle(fontSize: 24),
      )),
    );
  }
}
Hussain Humdani

Hussain Humdani

while ( ! ( succeed = try() ) );