1

I have a date string in flutter which i am trying to add week, month and year but not sure how to do it.

in android java, we can add weeks, month, year in the following way

Calendar cal = Calendar.getInstance();
cal.setTime('2019-09-04');

cal.add(Calendar.WEEK_OF_MONTH,1);  // add one week
cal.add(Calendar.WEEK_OF_MONTH, 2 );  // add two weeks
cal.add(Calendar.MONTH, 1);  // add # of month
cal.add(Calendar.MONTH, 3);  // add 3 months
cal.add(Calendar.YEAR, 1);  // add 1 year

however, i dont know how to add this in flutter. i know i can use duration but it only accept number of days cal.add(new Duration(days: 30)); if i use duration, then i need to figure out how many number of days in a month, week, or year and it is more math. with the above code in android java, adding weeks , months or year will be taken by android. is there a way for flutter to add weeks, months or year to a date?

for example: if i have 01/31/2019 and i want to add a month then new date should be 02/28/2019. if i want add a month to 02/28/2019 then output should be 03/31/2019

same goes for weeks and years. flutter should add a week to a date if specify or a year and so on. thanks in advance

yoohoo
  • 1,147
  • 4
  • 22
  • 39
  • Maybe you could figure out the rule of time, and make a plugin for It, or consider using [existed calandar plugin](https://pub.dev/packages/flutter_calendar_carousel). There is no equivalent class to `Calendar` in dart in my experience. – Tokenyet Sep 04 '19 at 15:23
  • By the way, the terrible `Calendar` class in Java was supplanted years by the modern *java.time* classes defined in JSR 310, specifically [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/ZonedDateTime.html). `LocalDate.parse( "2019-09-04" ).plusMonths( 3 ).plusWeeks( 2 )` – Basil Bourque Sep 05 '19 at 06:01

1 Answers1

6

You can find everything you need on this medium article: Top 7 Date methods

Let's suppose you have '2019-09-04', in Dart you have:

var myDate = DateTime.parse("2019-09-04 20:18:04Z");
myDate.add(Duration(days: 10, hours: 5)));

then print it out:

print(myDate.toLocal());

EDIT:

because of your comment below, to add years or month do as follow:

var date = new DateTime(2019, 9, 4);
var newDate = new DateTime(date.year + 1, date.month + 2, date.day);

You can find similar answer here: Add/Substract months/years to date in dart?

Marco
  • 676
  • 8
  • 12
  • hi Marco, thank you for your reply. however, using Duration i can only add days, hour. what if i want to add months or years? i will have to convert to the number of days etc. how do i add months to a date? or year? – yoohoo Sep 04 '19 at 16:47
  • 1
    date.month + 2 might push you into the following year. Does the constructor correct for that? Edit: yes, it does... nice. – Randal Schwartz Sep 11 '19 at 19:19