Get the Month and Year X number of months from now
From DataTime docunamtion:
Returns a new [DateTime] instance with [duration] added to [this].
var today = DateTime.now();
var fiftyDaysFromNow = today.add(const Duration(days: 50));
// adds 1 days
DateTime _future = DateTime.now().add(const Duration(days: 1));
//substracts 1 day
DateTime _tomorrow2 = DateTime.now().subtract(const Duration(days: 1));
Also this, credit ,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
Yonkee
Updated on December 28, 2022Comments
-
Yonkee over 1 year
I am attempting to generate a PageView that will display the Month and Year related to the number of times you swipe in either directon.
Example 1:
I swipe right twice, so I get Feb 2021
Example 2:
I swipe left 12 times, so I get April 2020
I have attempted to create a DateTime.now() and subtract an integer of months, but I'm not having much luck. I have looked at various plugins like DateUtils, but again no luck.
I have been at what should be a simple solution for while now and would appreciate a guidance.
The closet I get is the following which requires me to know the days in each month which isn't ideal
(DateTime.now().subtract(Duration(days: 90)).toString())
-
Yonkee about 3 yearsThanks, but I need to increment or decrement by months, not days.
-
Huthaifa Muayyad about 3 yearscheck my modified answer :)
-
Huthaifa Muayyad about 3 yearsYou're most welcome, kindly consider marking at we an answer if it solved your question :)
-
jamesdlin about 3 yearsBlindly incrementing or decrementing
date.month
won't work ifdate.day
isn't valid for that month. -
Huthaifa Muayyad about 3 yearsHe's not interested in days, but month and year. Also, days can be accounted for easily. Scope of the question was how to subtract months besides using i increments of 30
-
Randal Schwartz about 3 yearsAnd here's a video that goes into this with more detail: Proper Month and Day Arithmetic in Dart and Flutter: youtu.be/LpoBYgzKVwU
-
Randal Schwartz about 3 yearsAnd this breaks down if we're looking at the 30th or 31st day of the month. See my video at "Proper Month and Day Arithmetic in Dart and Flutter: youtu.be/LpoBYgzKVwU" for details.