Get dates on certain weekday between two dates - c#

I receive a start and end DateTime.
From this, I want to create a List<DateTime> of all the dates that are between these two dates, but only on specified weekdays, such as the Monday.

You can generate a list of dates as explained in Create an array or List of all dates between two dates:
public List<DateTime> GetDatesBetween(DateTime start, DateTime end)
{
var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToList();
return dates;
}
Now to filter this list to only include weekdays you're interested in is equally trivial by selecting only dates Where() the DayOfWeek property is one of the requested weekdays:
public List<DateTime> GetDatesBetween(DateTime start, DateTime end, params DayOfWeek[] weekdays)
{
bool allDays = weekdays == null || !weekdays.Any();
var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.Where(d => allDays || weekdays.Contains(d.DayOfWeek))
.ToList();
return dates;
}

Bellow function return a List<DateTime> contains all dates from startDate to endDate have given dayOfWeek:
public static List<DateTime> Get_DayofWeek_DatesBetween(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
List<DateTime> list = new List<DateTime>();
// Total dates in given range. "+ 1" include endDate
double totalDates = (endDate.Date - startDate.Date).TotalDays + 1;
// Find first "dayOfWeek" date from startDate
int i = dayOfWeek - startDate.DayOfWeek;
if (i < 0) i += 7;
// Add all "dayOfWeek" dates in given range
for (int j = i; j < totalDates; j += 7) list.Add(startDate.AddDays(j));
return list;
}

Related

how to check if dates exist in a list of all the weeks of a year

I've got an ASP.net C# application which creates a list of all the weeks in a given year. e.g. selected year 2019, and will produce 31/12/2019 to 06/01/2019 and so on. see attached image.
To produce this I am borrowing some code from an example I found on Stack Overflow here
Now I also have another list containing dates in the format dd/MM/yyyy, this is generated from an XML file, so I wanted to only show the weeks that match dates in the weeks of the year list and populate the drop down list when a date in my XML generated list is contained within it.
For example if I had a full week or even a day in my XML generated list which fell between the 31/12/2018 to 06/01/2019 I want to show it in the drop down list.
Similarly if the XML generated list doesn't contain at least a day from that week then don't show it.
I've pasted the code I used to get the weeks of a given year below.
I'm not sure of any easy way to compare both lists. Any help would be greatly appreciated.
public List<string> FetchWeeks(int year)
{
List<string> weeks = new List<string>();
DateTime startDate = new DateTime(year, 1, 1);
startDate = startDate.AddDays(1 - (int)startDate.DayOfWeek);
DateTime endDate = startDate.AddDays(6);
while (startDate.Year < 1 + year)
{
weeks.Add(string.Format("{0:dd/MM/yyyy} to {1:dd/MM/yyyy}", startDate, endDate));
startDate = startDate.AddDays(7);
endDate = endDate.AddDays(7);
}
//DropDownList1.Items.Add(weeks);
return weeks;
}
If were trying to compare lists to determine a set of valid weeks, I would try to determine an absolute week index and use that in my work. Since weeks are not impacted by things like leap years or other date oddities, we can just count in 7-day intervals from the beginning of a known of date range. Forgive me if my C# is rusty, but something to the effect of:
public int ToWeekIndex(DateTime date)
{
// Takes any date and maps it to a value that represents the week it resides in.
Timespan ts = date - DateTime.MinValue // Monday, January 1, 0001;
return ts.Days / 7; // Integer divide, drops the remainder.
}
public DateTime FromWeekIndex(int weekIndex)
{
// Takes a week index and returns the Monday from it.
Timespan ts = new Timespan(weekIndex * 7, 0, 0, 0); // Days, hours, minutes, seconds
return DateTime.MinValue + ts;
}
Then to build out your weeks, you could do something to the effect of pseudocode:
all_weeks = []
for date in January 1, 2019 to December 31, 2019 step 7 days:
week_index = ToWeekIndex(date)
week_start = FromWeekIndex(week_index)
week_end = week_start + 7 days - 1 second
all_weeks += [week_start, week_end]
instead of a list of string for dates, use a list of object that contains the week dates and a boolean defaulted to false.
public class WeekObj
{
public string Week { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool IsValid { get; set; }
};
List<WeekObj> weeks= new WeekObj();
weeks.add(new WeekObj { "week string", startDate, endDate, false });
Loop through your list of days, and for each day go through the list of weeks and set it to true if the day is between startDate and endDate (which is now in DateTime obj), do that for false dates, no need to recompare true dates.
public static bool Between(DateTime input, DateTime date1, DateTime date2)
{
return (input >= date1 && input <= date2);
}
This is the weeks in the Year data you already have -
class WeekData
{
public DateTime WeekStartDate { get; set; }
public DateTime WeekEndDate { get; set; }
public int WeekStartDay //Gets Day in the year for the Week Start Date
{
get { return WeekStartDate.DayOfYear; }
}
public int WeekEndDay //Gets Day in the year for the Week End Date
{
get { return WeekEndDate.DayOfYear; }
}
}
Dummy WeeksInTheYear data
List<WeekData> weeks = new List<WeekData>
{
new WeekData{WeekStartDate = new DateTime(2019,10,6), WeekEndDate = new DateTime(2019,10,12)},
new WeekData{WeekStartDate = new DateTime(2019,10,13), WeekEndDate = new DateTime(2019,10,19)},
new WeekData{WeekStartDate = new DateTime(2019,10,20), WeekEndDate = new DateTime(2019,10,26)},
new WeekData{WeekStartDate = new DateTime(2019,10,27), WeekEndDate = new DateTime(2019,11,2)}
};
Dummy Dates from the XML feed
List<DateTime> xmlDates = new List<DateTime> { new DateTime(2019, 11, 1), new DateTime(2019, 10, 12), new DateTime(2019, 10, 31) };
Filtering
var weeksINeed = new List<WeekData>();
foreach (var date in xmlDates)
{
var weekINeed = weeks.Where(x => x.WeekStartDay <= date.DayOfYear && x.WeekEndDay >= date.DayOfYear)
.FirstOrDefault();
if (!weeksINeed.Any(x => x.WeekStartDay == weekINeed.WeekStartDay))
{
weeksINeed.Add(weekINeed);
}
}
Output -
foreach (var weekdata in weeksINeed.OrderBy(x=>x.WeekStartDay))
{
Console.WriteLine($"WeekStartDate - {weekdata.WeekStartDate} WeekEndDate - {weekdata.WeekEndDate}");
}
Using some extension functions and LINQ, you can just generate the list directly from the XML Date List<string>.
First, an IEnumerable<> extension to select distinct by a lambda function:
public static class IEnumerableExt {
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer = null) {
var seenKeys = new HashSet<TKey>(comparer);
foreach (var e in src)
if (seenKeys.Add(keySelector(e)))
yield return e;
}
}
Then some calendar extensions using the built-in ISOWeek methods to get the week of year (Based on your week date ranges, I assume you are using ISO 8601 Weeks):
public static class CalendarExt {
public static int GetISO8601WeekOfYear(this DateTime aDate) => ISOWeek.GetWeekOfYear(aDate);
public static DateTime FirstDateOfYear(this DateTime d) => new DateTime(d.Year, 1, 1);
public static DateTime FirstDateOfISO8601Week(this DateTime aDate) => aDate.AddDays(-(((int)aDate.DayOfWeek + 6) % 7));
public static DateTime LastDateofISO8601Week(this DateTime aDate) => aDate.FirstDateOfISO8601Week().AddDays(6);
public static DateTime FirstDateOfISO8601Week(int year, int weekNum) => ISOWeek.ToDateTime(year, weekNum, DayOfWeek.Monday);
public static DateTime LastDateofISO8601Week(int year, int weekNum) => FirstDateOfISO8601Week(year, weekNum).AddDays(6);
// for .Net without ISOWeek
//public static DateTime FirstDateOfISO8601Week(this DateTime aDate) => aDate.AddDays(-(((int)aDate.DayOfWeek + 6) % 7));
//public static int GetISO8601WeekOfYear(this DateTime aDate) =>
// CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(aDate.AddDays(DayOfWeek.Monday <= aDate.DayOfWeek && aDate.DayOfWeek <= DayOfWeek.Wednesday ? 3 : 0), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
Finally, given your list of string dates from XML in xmlDateStrings, you can compute the week ranges list:
var currentCulture = CultureInfo.CurrentCulture;
var ans = xmlDateStrings.Select(ds => DateTime.ParseExact(ds, "dd/MM/yyyy", currentCulture))
.DistinctBy(d => d.GetISO8601WeekOfYear())
.OrderBy(d => d) // assume XML is unsorted
.Select(d => $"{d.FirstDateOfISO8601Week().ToString("dd/MM/yyyy")} to {d.LastDateofISO8601Week().ToString("dd/MM/yyyy")}")
.ToList();

How to return a list of weekend dates between 2 dates

At the moment I have this code to return a table of all dates between 2 dates. How could I change this to have it only return the weekend dates.
The purpose of this is to use the weekend dates to check against column headers in a DataGridView to "grey-out" the weekends. I hope that's clear.
static public List<string> GetDates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
{
days_list.Add(date.ToShortDateString());
}
return days_list;
}
Use the DateTime.DayOfWeek property.
https://msdn.microsoft.com/en-US/library/system.datetime.dayofweek(v=vs.110).aspx
static public List<string> GetDates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
days_list.Add(date.ToShortDateString());
}
return days_list;
You can create range of dates and then filter on them using DayOfWeek as #Vitor said:
static public List<DateTime> GetWeekendDates(DateTime start_date, DateTime end_date)
{
return Enumerable.Range(0, (int)((end_date- start_date).TotalDays) + 1)
.Select(n => StartDate.AddDays(n))
.Where(x=>x.DayOfWeek == DayOfWeek.Saturday
|| x.DayOfWeek == DayOfWeek.Sunday)
.ToList();
}
hope this solution will help you
DateTime startDate = new DateTime(2011,3,1);
DateTime endDate = DateTime.Now;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (var i = 0; i <= days; i++)
{
var testDate = startDate.AddDays(i);
switch (testDate.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine(testDate.ToShortDateString());
break;
}
}
in above code I am finding Saturday and Sunday between 1st March 2011 and today. So I have taken two variables called startDate and endDate. After that I have got difference between them and then via for loop I am checking that day of week is Saturday or Sunday

How to get All Dates in a given month in C#

I want to make a function that take month and year and return List<DateTime> filled with all dates in this month.
any help will be appreciated
Thanks in Advance
Here's a solution with LINQ:
public static List<DateTime> GetDates(int year, int month)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month)) // Days: 1, 2 ... 31 etc.
.Select(day => new DateTime(year, month, day)) // Map each day to a date
.ToList(); // Load dates into a list
}
And one with a for-loop:
public static List<DateTime> GetDates(int year, int month)
{
var dates = new List<DateTime>();
// Loop from the first day of the month until we hit the next month, moving forward a day at a time
for (var date = new DateTime(year, month, 1); date.Month == month; date = date.AddDays(1))
{
dates.Add(date);
}
return dates;
}
You might want to consider returning a streaming sequence of dates instead of List<DateTime>, letting the caller decide whether to load the dates into a list or array / post-process them / partially iterate them etc. For the LINQ version, you can accomplish this by removing the call to ToList(). For the for-loop, you would want to implement an iterator. In both cases, the return-type would have to be changed to IEnumerable<DateTime>.
Sample for pre-Linq Framework versions, using February 1999.
int year = 1999;
int month = 2;
List<DateTime> list = new List<DateTime>();
DateTime date = new DateTime(year, month, 1);
do
{
list.Add(date);
date = date.AddDays(1);
while (date.Month == month);
I am sure there might be better ways to do this. But, you could use this:
public List<DateTime> getAllDates(int year, int month)
{
var ret = new List<DateTime>();
for (int i=1; i<=DateTime.DaysInMonth(year,month); i++) {
ret.Add(new DateTime(year, month, i));
}
return ret;
}
Here you go:
public List<DateTime> AllDatesInAMonth(int month, int year)
{
var firstOftargetMonth = new DateTime(year, month, 1);
var firstOfNextMonth = firstOftargetMonth.AddMonths(1);
var allDates = new List<DateTime>();
for (DateTime date = firstOftargetMonth; date < firstOfNextMonth; date = date.AddDays(1) )
{
allDates.Add(date);
}
return allDates;
}
Iterates through the dates from the first of the month you want through to the last date that's less than the first of the next month.
PS: If this is homework, please tag it with "homework"!

Getting all DateTimes between two 'DateTime's in C#

I have two DateTimes, and I want to get all DateTimes between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function should return me a list of date (List), and it must contain 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010, and 05.01.2010.
I wrote a function like this. It works fine, if my dates are in a month. It won't work if my dates are like 01.01.2010 - 05.02.2010. Because the month changed, and my function can't handle it. Is there a function in C# that returns all dates between two dates? Or how can I handle month change?
public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
int starting = startingDate.Day;
int ending = endingDate.Day;
for (int i = starting; i <= ending; i++)
{
allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));
}
Question solved, see Tim Robinson's simple answer to use.
You can use DateTime objects directly in the loop, in place of your int. DateTime.AddDays handles month ends correctly.
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
allDates.Add(date);
How about something like this?
public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
{
return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
.Select(d => fromDate.AddDays(d));
}
Edit: Tested now. :)
public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
if (endingDate < startingDate)
{
throw new ArgumentException("endingDate should be after startingDate");
}
var ts = endingDate - startingDate;
for (int i = 0; i < ts.TotalDays; i++)
{
yield return startingDate.AddDays(i);
}
}
You were so close... just don't use the day, use the whole date.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}
Given a lowerdate value and higher date value in String and a frequency as the third parameter this method should return a dictionary of dates; where the key is the start value of a date range and the value is the respective range.
This works fine if the frequency is either weekly or monthly- you can customize it as per your need.
The date values passed should be in proper format or you might need to format it using tryParseExact or something like that.
protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency)
{
DateTime startDate, endDate;
startDate = Convert.ToDateTime(lowerDate);
endDate = Convert.ToDateTime(higherDate);
Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>();
while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate))
{
if (frequency.Equals("weekly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7));
startDate = startDate.AddDays(8);
}
if (frequency.Equals("monthly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1));
startDate = startDate.AddMonths(1).AddDays(1);
}
}
returnDict.Add(startDate, startDate + "-" + endDate);
return returnDict;
}
The top solutions will fail if the date includes different hours. Here is a solution getting all hours and all days:
All Days:
static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minues since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day);
//--Example Should return
//--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13
for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1))
{
days_list.Add(date.ToShortDateString());
}
return days_list;
}
All Hours:
static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> hours_24_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minutes since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0);
//--Example Should return
//--5:59AM - 6:01AM return 5am and 6am
for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1))
{
hours_24_list.Add(date.ToShortTimeString());
}
return hours_24_list;
}
Based on your starting code and using the features available at the time of writing, here is a quick console app to demonstrate how to do it - use AddDays() instead:
class Program
{
static void Main(string[] args)
{
GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5));
Console.ReadKey();
}
static List<DateTime> GetDates(DateTime startDate, DateTime endDate)
{
List<DateTime> dates = new List<DateTime>();
while ((startDate = startDate.AddDays(1)) < endDate)
dates.Add(startDate);
return dates;
}
}
Although I think the Enumerable.Range() answer from Matt is a nicer solution.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}

How do I loop through a date range?

I'm not even sure how to do this without using some horrible for loop/counter type solution. Here's the problem:
I'm given two dates, a start date and an end date and on a specified interval I need to take some action. For example: for every date between 3/10/2009 on every third day until 3/26/2009 I need to create an entry in a List. So my inputs would be:
DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;
and my output would be a list that has the following dates:
3/13/2009
3/16/2009
3/19/2009
3/22/2009
3/25/2009
So how the heck would I do something like this? I thought about using a for loop that would iterate between every day in the range with a separate counter like so:
int count = 0;
for(int i = 0; i < n; i++)
{
count++;
if(count >= DayInterval)
{
//take action
count = 0;
}
}
But it seems like there could be a better way?
Well, you'll need to loop over them one way or the other. I prefer defining a method like this:
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
Then you can use it like this:
foreach (DateTime day in EachDay(StartDate, EndDate))
// print it or whatever
In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3) in the loop instead of AddDays(1).
I have a Range class in MiscUtil which you could find useful. Combined with the various extension methods, you could do:
foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
.Step(DayInterval.Days())
{
// Do something with the date
}
(You may or may not want to exclude the end - I just thought I'd provide it as an example.)
This is basically a ready-rolled (and more general-purpose) form of mquander's solution.
For your example you can try
DateTime StartDate = new DateTime(2009, 3, 10);
DateTime EndDate = new DateTime(2009, 3, 26);
int DayInterval = 3;
List<DateTime> dateList = new List<DateTime>();
while (StartDate.AddDays(DayInterval) <= EndDate)
{
StartDate = StartDate.AddDays(DayInterval);
dateList.Add(StartDate);
}
Code from #mquander and #Yogurt The Wise used in extensions:
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Month == thru.Month; month = month.AddMonths(1))
yield return month;
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}
1 Year later, may it help someone,
This version includes a predicate, to be more flexible.
Usage
var today = DateTime.UtcNow;
var birthday = new DateTime(2018, 01, 01);
Daily to my birthday
var toBirthday = today.RangeTo(birthday);
Monthly to my birthday, Step 2 months
var toBirthday = today.RangeTo(birthday, x => x.AddMonths(2));
Yearly to my birthday
var toBirthday = today.RangeTo(birthday, x => x.AddYears(1));
Use RangeFrom instead
// same result
var fromToday = birthday.RangeFrom(today);
var toBirthday = today.RangeTo(birthday);
Implementation
public static class DateTimeExtensions
{
public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime> step = null)
{
if (step == null)
{
step = x => x.AddDays(1);
}
while (from < to)
{
yield return from;
from = step(from);
}
}
public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime> step = null)
{
return from.RangeTo(to, step);
}
}
Extras
You could throw an Exception if the fromDate > toDate, but I prefer to return an empty range instead []
DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;
for (DateTime dateTime=startDate;
dateTime < stopDate;
dateTime += TimeSpan.FromDays(interval))
{
}
DateTime begindate = Convert.ToDateTime("01/Jan/2018");
DateTime enddate = Convert.ToDateTime("12 Feb 2018");
while (begindate < enddate)
{
begindate= begindate.AddDays(1);
Console.WriteLine(begindate + " " + enddate);
}
According to the problem you can try this...
// looping between date range
while (startDate <= endDate)
{
//here will be your code block...
startDate = startDate.AddDays(1);
}
thanks......
DateTime startDate = new DateTime(2009, 3, 10);
DateTime stopDate = new DateTime(2009, 3, 26);
int interval = 3;
while ((startDate = startDate.AddDays(interval)) <= stopDate)
{
// do your thing
}
Here are my 2 cents in 2020.
Enumerable.Range(0, (endDate - startDate).Days + 1)
.ToList()
.Select(a => startDate.AddDays(a));
You can use the DateTime.AddDays() function to add your DayInterval to the StartDate and check to make sure it is less than the EndDate.
You might consider writing an iterator instead, which allows you to use normal 'for' loop syntax like '++'. I searched and found a similar question answered here on StackOverflow which gives pointers on making DateTime iterable.
you have to be careful here not to miss the dates when in the loop a better solution would be.
this gives you the first date of startdate and use it in the loop before incrementing it and it will process all the dates including the last date of enddate hence <= enddate.
so the above answer is the correct one.
while (startdate <= enddate)
{
// do something with the startdate
startdate = startdate.adddays(interval);
}
you can use this.
DateTime dt0 = new DateTime(2009, 3, 10);
DateTime dt1 = new DateTime(2009, 3, 26);
for (; dt0.Date <= dt1.Date; dt0=dt0.AddDays(3))
{
//Console.WriteLine(dt0.Date.ToString("yyyy-MM-dd"));
//take action
}
Iterate every 15 minutes
DateTime startDate = DateTime.Parse("2018-06-24 06:00");
DateTime endDate = DateTime.Parse("2018-06-24 11:45");
while (startDate.AddMinutes(15) <= endDate)
{
Console.WriteLine(startDate.ToString("yyyy-MM-dd HH:mm"));
startDate = startDate.AddMinutes(15);
}
#jacob-sobus and #mquander and #Yogurt not exactly correct.. If I need the next day I wait 00:00 time mostly
public static IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.NextDay())
yield return day;
}
public static IEnumerable<DateTime> EachMonth(DateTime from, DateTime thru)
{
for (var month = from.Date; month.Date <= thru.Date || month.Year == thru.Year && month.Month == thru.Month; month = month.NextMonth())
yield return month;
}
public static IEnumerable<DateTime> EachYear(DateTime from, DateTime thru)
{
for (var year = from.Date; year.Date <= thru.Date || year.Year == thru.Year; year = year.NextYear())
yield return year;
}
public static DateTime NextDay(this DateTime date)
{
return date.AddTicks(TimeSpan.TicksPerDay - date.TimeOfDay.Ticks);
}
public static DateTime NextMonth(this DateTime date)
{
return date.AddTicks(TimeSpan.TicksPerDay * DateTime.DaysInMonth(date.Year, date.Month) - (date.TimeOfDay.Ticks + TimeSpan.TicksPerDay * (date.Day - 1)));
}
public static DateTime NextYear(this DateTime date)
{
var yearTicks = (new DateTime(date.Year + 1, 1, 1) - new DateTime(date.Year, 1, 1)).Ticks;
var ticks = (date - new DateTime(date.Year, 1, 1)).Ticks;
return date.AddTicks(yearTicks - ticks);
}
public static IEnumerable<DateTime> EachDayTo(this DateTime dateFrom, DateTime dateTo)
{
return EachDay(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachMonthTo(this DateTime dateFrom, DateTime dateTo)
{
return EachMonth(dateFrom, dateTo);
}
public static IEnumerable<DateTime> EachYearTo(this DateTime dateFrom, DateTime dateTo)
{
return EachYear(dateFrom, dateTo);
}
If you convert your dates to OADate you can loop thru them as you would do with any double number.
DateTime startDate = new DateTime(2022, 1, 1);
DateTime endDate = new DateTime(2022, 12, 31);
for (double loopDate = startDate.ToOADate(); loopDate <= endDate.ToOADate(); loopDate++)
{
DateTime selectedDate;
selectedDate = DateTime.FromOADate(loopDate);
}

Categories

Resources