How to increment DateTime.now in dart

354

Yes you can, use DateTime.now().year to get the current year and then add as many years as you want. Like this:

final date = DateTime(DateTime.now().year + 20);
Share:
354
Emmon
Author by

Emmon

AngularJS, Angular, HTML 5, JavaScript, Ionic 3 Framework, Electron Framework, Bootstrap 4, Git Versioning tool, CSS,Php, ASP.NET API, Heroku deploy

Updated on January 01, 2023

Comments

  • Emmon
    Emmon over 1 year

    I am trying to use the DatePicker in flutter and I want to set the initialDate to DateTime.now() and the lastDate I want to set to DateTime.now() + 20yrs so it increments the year dynamically. Current I have my lastDate set to the year (2100), but this would cause a problem when the year 2101 reaches. So how can I modify my function to increase the lastDate dynamically?

    Here is my function:

    DateTime _date = DateTime.now();
    
    Future < Null > _checkInDate(BuildContext contex) async {
      DateTime ? _datePicker = await showDatePicker(
        context: context,
        builder: (BuildContext context, Widget ? child) {
          return Theme(
            data: ThemeData(
              primaryColor: Color(0xFFEF5350),
              colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.red)
              .copyWith(secondary: Color(0xFFFFF176)),
            ),
            child: child ? ? Text(""),
          );
        },
        initialDate: _date,
        firstDate: DateTime.now(),
        lastDate: DateTime(2100), //how can i increase the lastDate dynamically?
      );
      if (_datePicker != null && _datePicker != _date) {
        _checkInController.text = DateFormat('dd-MM-yyyy').format(_datePicker);
      }
    }