Nitneuq
Nitneuq

Reputation: 5012

How to increase or decrease days from a Dateformat ouptput in flutter?

Hello I have this format date example: 4 jun 2019

  DateTime now = DateTime.now();
               formattedDate = DateFormat.yMMMMd("fr_FR").format(now);

I tried now to increase or decrease days after pressed on the button but the previous code isn't compatible with :

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

Upvotes: 1

Views: 1201

Answers (2)

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

Increase and Decrease of the day can be done by DateTime class

Initialize DateFormat which needed to be shown

  var _inputFormat = DateFormat('EE, d MMM yyyy');
  var _selectedDate = DateTime.now();

Code:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
            height: 40,
            padding: EdgeInsets.symmetric(horizontal: 8),
            margin: EdgeInsets.symmetric(horizontal: 18),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.blue,
            ),
            child: Row(
              children: [
                InkWell(
                  onTap: () {
                    _selectedDate = DateTime(_selectedDate.year,
                        _selectedDate.month, _selectedDate.day - 1);
                    setState(() {});
                  },
                  child: Icon(Icons.exposure_minus_1_sharp),
                ),
                const Spacer(),
                Text(
                  _inputFormat.format(_selectedDate),
                ),
                Spacer(),
                InkWell(
                  onTap: () {
                    _selectedDate = DateTime(_selectedDate.year,
                        _selectedDate.month, _selectedDate.day + 1);
                    print(_inputFormat.format(_selectedDate));
                    setState(() {});
                  },
                  child: Icon(Icons.plus_one),
                ),
              ],
            )),
      ),
    );

Output:

enter image description here

Upvotes: 0

siega
siega

Reputation: 2878

First: define your formatter:

final _dateFormatter = DateFormat.yMMMMd("fr_FR");

Then you need to have a method that receives your date and the number of days (positive will increase days, negative will decrease):

DateTime changeDate(DateTime dtObj, int numberOfDays) {
    return dtObj.add(Duration(days: numberOfDays));
}

Then, when you need to show your date, you can format it:

String formattedDate = _dateFormatter.format(previouslyChangedDate);
print(formattedDate); //prints as: 4 juin 2019

Upvotes: 2

Related Questions