2

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
  • 1,781
  • 3
  • 31
  • 56

2 Answers2

1

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
Huthaifa Muayyad
  • 11,321
  • 3
  • 17
  • 49
0

Y'all are going about it wrong. Presuming 24 hours in a day, or 30 days in a month, is just wrong. Here's how to always get midnight the first of the month, 7 months before today:

void main() {
  var n = DateTime.now();
  print(DateTime(n.year, n.month - 7, 1));
}

Just use DateTime constructors. They wrap around just fine. Works at month's end as well:

void main() {
  var n = DateTime(2021, 2, 28);
  print(DateTime(n.year, n.month, n.day + 1));
  n = DateTime(2020, 2, 28);
  print(DateTime(n.year, n.month, n.day + 1));
}

Which correctly shows 3/1 for 2021, and 2/29 for 2020, as it was a leap year.

Stop adding 24-hour days! I've got a video that explains why.... https://www.youtube.com/watch?v=usFSVUEadyo

And 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
  • 39,428
  • 4
  • 43
  • 70
  • And here's a video that goes into this with more detail: Proper Month and Day Arithmetic in Dart and Flutter: https://youtu.be/LpoBYgzKVwU – Randal Schwartz Apr 04 '21 at 00:05