How to Format DateTime In Flutter

How to Format DateTime In Flutter ?

Many times it may happen that the user needs to display the current  DateTime in a Text Widget. Depending on the user requirement user, sometimes developer needs to display Date Time as per the Client Requirement like DD/MM/YYYY or MM/DD/YYYY.

formatting date & time in default US standard does not required any specific command.

print(DateFormat.yMMMd().format(DateTime.now()));

So in this article, We will discuss How to Format DateTime In Flutter.

Learn How to Format DateTime In Flutter?

Depending on a client’s requirement we need to format DateTime. Users can take a look at intl package.

This package provides internationalization and localization facilities, including message translation, plurals and genders, date/number formatting and parsing, and bidirectional text.

To use the above package we need to import it like the below:

import 'package:intl/intl.dart';

Now we need to current DateTime using the below code Snippet.

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Converting DateTime object to String

String string = dateFormat.format(DateTime.now());

Converting String to DateTime object

DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");

Users can also create a custom function like the below:

todayDate() {
    var now = new DateTime.now();
    var formatter = new DateFormat('dd-MM-yyyy');
    String formattedTime = DateFormat('kk:mm:a').format(now);
    String formattedDate = formatter.format(now);
    print(formattedTime);
    print(formattedDate);
  }

So the Output will be as follows:

01:41:AM
22-10-2020

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';
Use the String split method to remove :00.000
var formatedTime = currentTime.toString().split(':')
Text(formatedTime[0])

Code for YYYY-MM-DD HH:MM: SS format without using a library

var stringList =  DateTime.now().toIso8601String().split(new RegExp(r"[T\.]"));
var formatedDate = "${stringList[0]} ${stringList[1]}";

Conclusion:

So in this article, We have been through how to Format DateTime In Flutter.

Keep Learning!!! Keep Fluttering !!!

Still, need Support for Flutter Development? Do let us know, we would love to assist you.

Get The Assistance

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on