How to create a Date list with a specific day

Asked

Viewed 2,432 times

15

I am working on ASP with MVC 4, and I hold create a list of dates from the data entered by the user. For example, the user inserts 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 inserts the Day 19 start date to 05/02/2014 and end date for 20/05/2014 I in the controller have to generate a date list of type:

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

  • In the above example, the date 19/05/2014 is missing?

2 answers

7


You can use the Addmonths(), various languages have a method similar to that implemented.

Follow the example using as a basis the current date, and incrementing two months to it:

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

In your case, the difference would be to create the initial date based on user input and store it in a list.

Example of use

    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

  • Yes, but that’s not the point. The point is I’m generating dates between start dates and end dates. How do I validate to create only dates between these two dates.

  • You compare the two dates to know if copntinua generating others, or if it is the process. I added another code snippet as an example

  • Yes, I’ve already found the solution. Thanks anyway for the help!

1

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

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());
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.