Add/Subtract months/years to date in dart?

后端 未结 7 2243
感动是毒
感动是毒 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:40

    Use the add and subtract methods with a Duration object to create a new DateTime object based on another.

    var date1 = DateTime.parse("1995-07-20 20:18:04");
    
    var newDate = date1.add(Duration(days: 366));
    
    print(newDate); // => 1996-07-20 20:18:04.000
    

    Notice that the duration being added is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days later.

    Be careful when working with dates in local time.

提交回复
热议问题