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.
Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Flutter Agency is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.