I am trying to display the current DateTime
in a Text
widget after tapping on a button. The following works, but I'd like to change the format.
Current approach
DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
Text('$currentTime'),
Result
YYYY-MM-JJ HH-MM:00.000
Question
How can I remove the :00.000
part?
You can use DateFormat
from intl package.
import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
Add intl
package to your pubspec.yaml
file.
import 'package:intl/intl.dart';
DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
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");
With this approach, there is no need to import any library.
DateTime now = DateTime.now();
String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString()}-${now.minute.toString()}";
Output
2020-12-05 14:57
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
import 'package:jiffy/jiffy.dart';
var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");
You can also do the following
var a = Jiffy().yMMMMd; // October 18, 2019
And you can also pass in your DateTime object, A string and an array
var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019
var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019
var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019
Here's my simple solution. That does not require any dependency.
However, the date will be in string format. If you want the time then change the substring values
print(new DateTime.now()
.toString()
.substring(0,10)
); // 2020-06-10
there is some change since the 0.16 so here how i did,
import in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
then use
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
Use this function
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);
}
Output:
08:41:AM
21-12-2019
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 String split method to remove :00.000
var formatedTime = currentTime.toString().split(':')
Text(formatedTime[0])
======= OR USE BELOW code for YYYY-MM-DD HH:MM:SS format without using library ====
var stringList = DateTime.now().toIso8601String().split(new RegExp(r"[T\.]"));
var formatedDate = "${stringList[0]} ${stringList[1]}";
Source: Stackoverflow.com