Reputation: 34158
I have two date time ranges 8/27/2011 and 8/31/2011 how i can make get all days ? like that : 8/28/2011, 8/29/2011 and 8/30/2011
thanks
Upvotes: 2
Views: 5295
Reputation: 3328
To piggy back off of davecoulter, if you need to do this all over your application for your DateTime objects, you might want to define an extenion method for your DateTime object.
void Main()
{
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
foreach (DateTime dateTime in today.ListAllDates(nextWeek))
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
}
public static class DateTimeExtenions
{
public static IEnumerable<DateTime> ListAllDates(this DateTime lhs, DateTime futureDate)
{
List<DateTime> dateRange = new List<DateTime>();
TimeSpan difference = (futureDate - lhs);
for(int i = 0; i <= difference.Days; i++)
{
dateRange.Add(lhs.AddDays(i));
}
return dateRange;
}
}
You can copy this straight into LinqPad and run as program to test it out.
Upvotes: 3
Reputation: 19733
using System;
using System.Linq;
var startDate = new DateTime(2011, 9, 1);
var days = Enumerable.Range(0, 10).Select(n => startDate.AddDays(n));
Upvotes: 3
Reputation: 1826
Here is a code snippet to get all days between a start and end date inclusive:
DateTime today = new DateTime(2011, 8, 29);
DateTime nextWeek = new DateTime(2011, 9, 4);
TimeSpan difference = nextWeek - today;
List<DateTime> days = new List<DateTime>();
for (int i = 0; i <= difference.Days; i++)
{
days.Add(today.AddDays(i));
}
foreach (var dateTime in days)
{
Console.WriteLine(dateTime);
}
Console.ReadLine();
Output:
8/29/2011 12:00:00 AM
8/30/2011 12:00:00 AM
8/31/2011 12:00:00 AM
9/1/2011 12:00:00 AM
9/2/2011 12:00:00 AM
9/3/2011 12:00:00 AM
9/4/2011 12:00:00 AM
Upvotes: 4
Reputation: 2801
Create a new date from both datetimes datetime to make sure that it they are at the start of the day. Then run a for loop that works from starttime.Ticks to endtime.Ticks and increments by TimeSpan.TicksPerDay and create a new DateTime that you add to a list for every value. The example below will not include the end date but you can easily fix that.
var start= new DateTime(2009,01,01).Ticks;
var end= new DateTime(2009,01,10).Ticks;
List<DateTime> dates = new List<DateTime>();
for (var i = start; i < end; i+=TimeSpan.TicksPerDay) {
dates.Add(new DateTime(i));
}
Or you could loop through between them and call the AddDays method.
Upvotes: 1