How to Get Current Date and Time on Flutter

In this example, we are going to show you the easiest way to get the current date and time on the Flutter app with the dart. We will also show you to get date and time with different kinds of formats as well. See below for more details.

String datetime = DateTime.now().toString();
print(datetime);
// 2021-08-27 19:14:57.142575

var dt = DateTime.now();
print(dt.year); 
// -> Year | Output: 2021

print(dt.month); 
// -> Month | Output: 8

print(dt.day); 
// -> Day | Output: 27

print(dt.hour); 
// -> Hour | Output: 19

print(dt.minute); 
// -> Minute | Output: 19

print(dt.second); 
// -> Second | Output: 2

To get date and time on a formatted string, first, you need to add intl flutter package on your project dependency by adding the following lines on pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  intl: ^0.17.0

Import:

import  'package:intl/intl.dart';

Now to get date on a formatted string, follow the steps below:

String cdate = DateFormat("yyyy-MM-dd").format(DateTime.now());
print(cdate);
// output: 2021-08-27

String cdate1 = DateFormat("EEEEE, dd, yyyy").format(DateTime.now());
print(cdate1);
// output: Friday, 27, 2021

String cdate2 = DateFormat("MMMM, dd, yyyy").format(DateTime.now());
print(cdate2);
//output:  August, 27, 2021

String cdate3 = DateFormat("MMM, EEE, yyyy").format(DateTime.now());
print(cdate3);
// output:  Aug, Fri, 2021

String tdata = DateFormat("HH:mm:ss").format(DateTime.now());
print(tdata);
// output: 19:36:01

String tdata = DateFormat("hh:mm:ss a").format(DateTime.now());
print(tdata);
// output: 07:38:57 PM

In this way, you can get the current date and time on the formatted string.

No any Comments on this Article


Please Wait...