Flutter is a cross-platform mobile app development framework that allows developers to write a single codebase for both iOS and Android. Dart is used as the programming language to develop Flutter mobile applications.
The current date can be easily obtained in Flutter using the DateTime class. This class provides various methods for manipulating dates and times, such as getting the current date and time, adding or subtracting days or months, and more.
We can use the DateTime.now() function to get the current date in Flutter. You do not need to import anything to use the DateTime module. This is an in-built module of Dart and you can use its now() function to get the current date with time.
Syntax
DateTime.now()
Code example
DateTime current_date = DateTime.now();
print(current_date);
Output
2022-05-26 17:16:00.249516
Code example 2 - Convert DateTime to string
DateTime datetime = DateTime.now();
String dateStr = datetime.toString();
print(dateStr);
We can use the below code to get the current date in string format using the below code.
DateTime today = DateTime.now();
String dateStr = "${today.day}-${today.month}-${today.year}";
print(dateStr);
Output
27-5-2022
Here, we will learn how to get the current date without time using the intl package. The intl package is a powerful standard library that provides many internationalization features, including date and time formatting.
First, install the intl package
dependencies:
intl: ^0.17.0
Or you can also check the package here.
Second, import the package into your Flutter project,
import 'package:intl/intl.dart';
Finally, use the below code to get the current date in a specific format
Today's date in yyyy-mm-dd format
String currentDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
print(currentDate);
Output
2022-05-26
Today's date in dd-mm-yyyy format
var today = DateTime.now();
var dateFormat = DateFormat('dd-MM-yyyy');
String currentDate = dateFormat.format(today);
print(currentDate);
Output
26-05-2022
Write the above code in single line
String currentDate = DateFormat('dd-MM-yyyy').format(DateTime.now());
print(currentDate);
DateTime today = DateTime.now();
String dateStr = today.toString().substring(0, 10);
print(dateStr);
0 Comments