user393267
user393267

Reputation:

Work around immutable datetime to add a day in a loop

I am looking for a way to increment a datetime in a loop.

the datetime itself is not mutable, so when I call AddDays() I have to use a different variable.

But doing so, then the new variable, wich is a datetime, will be unmutable, so I need to crate a new variable to add yet another day, and so on.

How do you actually make a loop where you add a day every time, without create a new variable every time?

public void AddDayToDate()
{
    public DateTime startingdate = new DateTime(2016,1,1);
    public DateTime updated_date;
    while (true)
    {
        updated_date = startingdate.AddDays(1);
        print(updated_date);
    }
}

Upvotes: 1

Views: 314

Answers (1)

Rob
Rob

Reputation: 27357

You nearly had it:

public DateTime startingdate = new DateTime(2016,1,1);
public void AddDayToDate()
{
    var updatedDate = startingDate;
    while (true)
    {
        updatedDate = updatedDate.AddDays(1);
        print(updatedDate);
    }
}

Your use case is not too clear to me, but it's also perfectly valid to modify the original date as well:

public DateTime startingdate = new DateTime(2016,1,1);
public void AddDayToDate()
{
    while (true)
    {
        startingdate = startingdate.AddDays(1);
        print(startingdate);
    }
}

As for the question about mutability; You are supposed to create a new object (and possibly a new variable) every time you change a date. It's designed that way, and there's no real work-around (at least none that wouldn't be hacky).

Dates don't change. February 12th 2016 will never be February 13th 2016. A particular date you are referring to, however, can change - which is the same as changing the variable to a new date.

If you plan an event on February 12th 2016, and decide to move it to February 13th 2016, would you logically change February 12th to forever be February 13th, or would you simply give the event a new date?

Upvotes: 8

Related Questions