Reputation: 37
I'm trying to populate my listbox from today's date until the next 30 days. My current code populates my textbox from the current month. How do I only get the value of the date today until the next 30 days.
int year = 2018;
int month = 2;
DateTime date = new DateTime(year, month, 1);
//DateTime Today = DateTime.Today;
//DateTime expiryDate = Today.AddDays(30);
do
{
date = date.AddDays(1);
var dateonly = date.ToShortDateString();
listBox1.Items.Add(dateonly);
}
while (date.Month == month);
Upvotes: 0
Views: 481
Reputation: 819
You can use Enumerable.Range:
DateTime date = new DateTime(year, month, 1);
Enumerable.Range(0, 30).ToList().ForEach(day => listBox1.Items.Add(date.AddDays(day).ToShortDateString()));
Upvotes: 0
Reputation: 29036
So you are aware about the limit(here 30 days). Then why not something like this, by using a counter?
DateTime currentDate = DateTime.Now;
for (int dayCount = 1; dayCount <= 30; dayCount++)
{
var date = currentDate.AddDays(dayCount);
var dateonly = date.ToShortDateString();
listBox1.Items.Add(dateonly);
}
The for
loop should be for (int dayCount = 0; dayCount < 30; dayCount++)
if you want to include current date in the list
Upvotes: 1