How to format DateTime in Flutter

前端 未结 9 1752
悲哀的现实
悲哀的现实 2020-12-04 10:28

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.

相关标签:
9条回答
  • 2020-12-04 11:23

    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");
    
    0 讨论(0)
  • 2020-12-04 11:25

    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
    
    0 讨论(0)
  • 2020-12-04 11:26

    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)
    
    0 讨论(0)
提交回复
热议问题