Add/Subtract months/years to date in dart?

后端 未结 7 2080
感动是毒
感动是毒 2021-01-01 08:57

I saw that in dart there is a class Duration but it cant be used add/subtract years or month. How did you managed this issue, I need to subtract 6 months from an date. Is th

相关标签:
7条回答
  • 2021-01-01 09:51

    You can use subtract and add methods

    Subtract

    Add

    But you have to reassign the result to the variable, which means:

    This wouldn't work

     date1.add(Duration(days: 1, hours: 23)));
    

    But this will:

     date1 = date1.add(Duration(days: 1, hours: 23)));
    

    For example:

     void main() {
      var d = DateTime.utc(2020, 05, 27, 0, 0, 0);
      d.add(Duration(days: 1, hours: 23));
      // the prev line has no effect on the value of d
      print(d); // prints: 2020-05-27 00:00:00.000Z
    
      //But
      d = d.add(Duration(days: 1, hours: 23));
      print(d); // prints: 2020-05-28 23:00:00.000Z
    }
    

    Dartpad link

    0 讨论(0)
提交回复
热议问题