androidiosflutterdatetimedart

How to format DateTime in Flutter


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?


Solution

  • 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);