Format Dates in Flutter

The article from geeksforgeeks

The Dart in-built method, for formatting, dates in Flutter according to the requirements is very limited and restrictive. While dealing with dates it should be in human-readable format but unfortunately, there’s no way of formatting dates in flutter unless you make use of a third-party package.

In this article, we will look into one such package known as the intl package.

intl package

Using intl package

Add the following dependencies to your pubspec.yaml file, you can find the latest dependencies here.

1
2
dependencies:
  intl: ^0.17.0

Add using terminal

You can also get the latest intl library using terminal easily:

1
flutter pub add intl

Import it: That’s it now import intl package in your Dart code:

1
import 'package:intl/intl.dart';

Still, if you face any error using intl, simply use the following command:

1
flutter pub get

Now let’s take a look at the below example.

Example

In the below code we will not be using the intl package for formatting. Also, take a look at the output of the below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import 'package:flutter/material.dart';

void main() {
runApp(dateDemo());
}

class dateDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
	return MaterialApp(
	
	// browser tab title
	title: "Geeksforgeeks",
	
	// Body
	home: Scaffold(
		
		// AppBar
		appBar: AppBar(
			
			// AppBar color
			backgroundColor: Colors.green.shade900,
			
			// AppBar title
			title: Text("Geeksforgeeks"),		
		),
		
		// Container or Wrapper
		body: Container(						
			margin: EdgeInsets.fromLTRB(95, 80, 0, 0),
			
			// printing text on screen
			child: Text(						
			
			// Formatted Date
			// Builtin format / without formatting
			DateTime.now().toString(),		
			style: TextStyle(
				
				// Styling text
				fontWeight: FontWeight.bold, fontSize: 30),
			),
		)),
	);
}
}

More DateFormat Functions

Use Description Example
DateFormat.yMMMEd().format(date) Day Name ,Month Name ,Date,Year Fri, Sep 3, 2021
DateFormat.MEd().format(date) Day Name,Month/Date in Numbers Fri , 9/3
DateFormat.MMMMEEEEd().format(date)) DayName,MonthName Date Friday ,September 3
DateFormat.yMMMMEEEEd().format(date)) DayName ,MonthName Date,Year Friday ,September 3,2021
DateFormat.EEEE().format(date) Full DayName only Friday
DateFormat.E().format(date) Short DayName Fri
DateFormat.M().format(date) Month-Number 9
DateFormat.MMM().format(date) Short MonthName Sep
DateFormat.LLLL().format(date) Full MonthName September
DateFormat.j().format(date) Current Time only 4 PM