bree
bree

Reputation: 11

How to loop selected Month/Date/Year with 30 days interval in C#

How to code this..

I selected date in dateTimePicker and I wanted to loop that with 24 months. Example

I selected

4/4/2018
5/4/2018
6/4/2018
7/4/2018
...
...
...
4/4/2020 (24 months)

Upvotes: 0

Views: 1016

Answers (5)

Hesam Faridmehr
Hesam Faridmehr

Reputation: 1196

You can use AddMonths method of DateTime class.

var dateTime = DateTime.Parse("4/4/2018");
var monthCount = 24;

while (monthCount-- > 0)
    dateTime = dateTime.AddMonths(1);

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

It seems that you want a for loop, either with 30 days step (as in the question's title)

for (DateTime date = dateTimePicker.Value.Date; 
     date <= dateTimePicker.Value.AddYears(2); // or .AddMonths(24) 
     date = date.AddDays(30)) {
  ... 
}

or 1 month one (as in the example provided; since, say, 4th May + 30 days is 3d June, not 4th June):

for (DateTime date = dateTimePicker.Value.Date; 
     date <= dateTimePicker.Value.AddYears(2); 
     date = date.AddMonths(1)) {
  ... 
}

Upvotes: 2

Flocke
Flocke

Reputation: 834

Try this snipped:

DateTime dt = ... // Get the value from your Datetimepicker.
for (int i = 0; i <= 24; i++) {
    // do something, e.g. print the date; 
    dt= dt.AddMonths(1);
}

Upvotes: 0

I.Manev
I.Manev

Reputation: 727

Use DateTime.AddMonths Method and simple for loop:

 var date = new DateTime(2018, 4, 4); // use datetimepicker value instead
 for (int ctr = 0; ctr <= 24; ctr++)
    Console.WriteLine(date.AddMonths(ctr).ToString("d"));

Upvotes: 0

Gaurang Dave
Gaurang Dave

Reputation: 4046

List<DateTime> list = new List<DateTime>();
DateTime dt = DateTime.Now;

list.Add(dt);

for (int i = 1 ; i < 24; i++)
{
    list.Add(dt.AddMonths(i));
}

In list , you will get all 24 dates as you asked in question.

Upvotes: 0

Related Questions