How to create a list of dates with specific day

15

I'm working on ASP with MVC 4, and I create a list of dates from the data entered by the user. For example, the user enters the day of the month in which a certain occurrence will be made. It also inserts the start date where it will start and the end date to generate the dates. For example:

The user enters Day% with% start date to 19 and end date to 05/02/2014 In the controller I have to generate a list of dates of type:

02/19/2014
03/19/2014
04/19/2014

    
asked by anonymous 04.02.2014 / 11:19

2 answers

7

You can use AddMonths () , several languages have a method similar to that implemented.

Follow the example based on the current date, and increasing it by two months:

    DateTime now = DateTime.Now;  
    DateTime modifiedDatetime = now.AddMonths(2); 

In your case, the difference would be in creating the start date based on user input and storing it in a list.

Use example

    var DataGerada = new DateTime(DataIni.Year, DataIni.Month, dia);

    int i = DateTime.Compare(DataGerada,DataFim);

    if( i > 0){
            //DataGerada é maior do que DataFim, interrompa processo e retorne a lista
    }else{
            //DataGerada é menor ou igual que DataFim, adicione DataGerada à lista
    }

    //A cada iteração execute novamente DataGerada.AddMonths(1)

DateTime.Compare Reference

    
04.02.2014 / 12:08
1

Using the approach suggested by Guilherme, I made a small implementation of a method that returns dates in the desired range.

public List<DateTime> GerarDatas(DateTime inicio, DateTime fim, int dia)
{
    List<DateTime> datas = new List<DateTime>();

    DateTime data = inicio.AddDays(dia - inicio.Day);
    if (inicio.Day > dia)
    {
        data = data.AddMonths(1);
    }

    while (data < fim)
    {
        datas.Add(data);
        data = data.AddMonths(1);
    }

    return datas;
}

How to use:

List<DateTime> datas = program.GerarDatas(new DateTime(2014, 2, 5), new DateTime(2014, 5, 20), 19);
foreach (DateTime data in datas)
{
    Console.WriteLine(data.ToShortDateString());
}
    
29.05.2014 / 22:03