0

if i'm tried to get last month date using mentioned code i'm getting date like 347/12/2019 instead of 13/12/2019

  DateTime _startDate = DateTime.now();
  DateTime _endDate = DateTime.now().add(Duration(days: 7));
  DateTime Date=DateTime.now();

  Future datePicker(BuildContext context) async {

    final List<DateTime> picked = await DateRagePicker.showDatePicker(
        context: context,
        initialFirstDate: _startDate,
        initialLastDate: _endDate,
        firstDate: new DateTime(DateTime.now().year - 50),
        lastDate: new DateTime(DateTime.now().year + 50),
    );
    if (picked != null && picked.length == 2) {
      setState(() {
        _startDate = picked[0];
        _endDate = picked[1];
      });
    }

  }
onTap: (){
 setState(() {
    _startDate=new DateTime(Date.year, Date.month - 1, Date.day);
    _endDate=DateTime.now();
    Navigator.pop(context);
});
}

SRC URL

Gokul Sundar
  • 305
  • 1
  • 3
  • 12

2 Answers2

0

This works fine if what you are trying to do is to get the month before today's month

  DateTime now = DateTime.now();
  DateTime pastMonthFromNow = DateTime(now.year, now.month-1, now.day);
  print(pastMonthFromNow);

enter image description here

orimdominic
  • 995
  • 10
  • 23
Federick Jonathan
  • 2,726
  • 2
  • 13
  • 26
0

You have done everything correct, but a small tweak is required in setState(). Replace your setState as below.

setState(() {
     _startDate=new DateTime(_startDate.year, _startDate.month - 1, _startDate.day);
    _endDate=DateTime.now();
    Navigator.pop(context);
});

Check the gist here https://gist.github.com/ragu-swaminathan/4c2dd2f49f585397e67143d34707f7cb

Swaminathan V
  • 4,663
  • 2
  • 22
  • 32