Flutter : How to change format dateTime with mounth in String?

北慕城南 提交于 2021-01-29 18:19:45

问题


hello I don't succeded to output this code in this format ( 04 Juin 2019 )

var now = new DateTime.now();
var daysfromnow = now.add(new Duration(days: changedate));

RegExp regExp = new RegExp(       
    r"(^\S*)",
);

var match = regExp.firstMatch("$daysfromnow");
daysfromnow_modify = match.group(1);

current outpub : 2019-06-04

expected output : 04 juin 2019

Update:

I tried to format but I don't succeded to change days when I press button...

here is the new code

     new IconButton(
              icon: Icon(Icons.keyboard_arrow_left),

              onPressed: () {
        setState(() {
          changedate--;
          DateTime now = DateTime.now();
          formattedDate = DateFormat.yMMMMd("en_FR").format(now);
          daysfromnow = formattedDate.add(new Duration(days: changedate));  //add can't be a String ...
});
)}

I tried this also ..

 formattedDate = DateFormat.yMMMMd("en_FR").now.add(new Duration(days: changedate));

回答1:


You can try to use a DateFormat, just include intl dependency to your pubspec.yaml

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat("dMMMMy")format(now);
print(formattedDate);

Depending on what your requirements is, you can look at DateFormat

Some examples taken from DateFormat-class to help you a bit more.

String formattedDate = DateFormat.yMd(); // 7/10/1996
String formattedDate = DateFormat("yMd"); // 7/10/1996
String formattedDate = DateFormat.yMMMMd("en_US"); // July 10, 1996
String formattedDate = DateFormat.yMMMMd("en_FR"); // 10 July 1996 // Locale French

UPDATE

First add the value to the date and then call the format.

Example:

setState(() {
    changedate--;
    var now = DateTime.now(); // Current Date
    var daysFromNow = now.add(new Duration(days: changedate); // Assuming this is the date you want (Variable is unclear)

    String formattedDate = DateFormat.yMMMMd('en_FR').format(daysFromNow);
    print(formattedDate);

   // daysfromnow = formattedDate // This cannot exist due to the formattedDate is a `String`
});


来源:https://stackoverflow.com/questions/56442392/flutter-how-to-change-format-datetime-with-mounth-in-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!