Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/Subtract months/years to date in dart?

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 there something like moment.js for dart or something around? Thank you

like image 704
cosinus Avatar asked Feb 20 '19 17:02

cosinus


People also ask

How do you subtract dates in darts?

subtract methodDateTime today = new DateTime. now(); DateTime fiftyDaysAgo = today. subtract(new Duration(days: 50)); Notice that the duration being subtracted is actually 50 * 24 * 60 * 60 seconds.

How do you add months to darts?

You can add and subtract using the following units. To add 6 Months. DateTime d = Jiffy(). add(months: 6); // 2020-04-26 10:05:57.469367 // You can also add you own Datetime object DateTime d = Jiffy(DateTime(2018, 1, 13)).

How do you subtract duration in Flutter?

In Flutter and Dart, you can subtract two dates by using the DateTime. difference method. The result is a duration. The DateTime class also has a method named subtract.


3 Answers

Okay so you can do that in two steps, taken from @zoechi (a big contributor to Flutter):

Define the base time, let us say:

var date = new DateTime(2018, 1, 13);

Now, you want the new date:

var newDate = new DateTime(date.year, date.month - 1, date.day);

And you will get

2017-12-13
like image 185
Smily Avatar answered Oct 26 '22 23:10

Smily


You can use the subtract and add methods

 date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56)); 

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

Flutter Docs:

Subtract

Add

like image 21
aabiro Avatar answered Oct 26 '22 23:10

aabiro


Try out this package, Jiffy. Adds and subtracts date time with respect to how many days there are in a month and also leap years. It follows the simple syntax of momentjs

You can add and subtract using the following units

years, months, weeks, days, hours, minutes, seconds and milliseconds

To add 6 months

DateTime d = Jiffy().add(months: 6).dateTime; // 2020-04-26 10:05:57.469367
// You can also add you own Datetime object
DateTime d = Jiffy(DateTime(2018, 1, 13)).add(months: 6).dateTime; // 2018-07-13 00:00:00.000

You can also do chaining using dart method cascading

var jiffy = Jiffy().add(months: 5, years: 1);

DateTime d = jiffy.dateTime; // 2021-03-26 10:07:10.316874
// you can also format with ease
String s = jiffy.format("yyyy, MMM"); // 2021, Mar
// or default formats
String s = jiffy.yMMMMEEEEdjm; // Friday, March 26, 2021 10:08 AM
like image 32
Jama Mohamed Avatar answered Oct 26 '22 23:10

Jama Mohamed