Get Monday's date every week in between two dates - c#

How to get a Monday dates after every week in between from given start date and end date
For example
Start date : 28-12-2018
End date : 29-12-2019
So the following dates should be in the list
Monday : 3-12-2018
Monday : 14-01-2019
Monday : 28-01-2019
Monday : 11-02-2019
This my code: I am unable to find the every week in between from the range.how to identify dates that its from 1 week.
Any help will be appropriated
DateTime startDate = LimitVmodel.StartDate;
DateTime endDate = LimitVmodel.EndDate;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (long i = 0; i <= days; i++)
// for (DateTime date = TIR.NetCore.PersianDateTime.ConvertShToM(LimitVmodel.StartDate); date <= TIR.NetCore.PersianDateTime.ConvertShToM(LimitVmodel.EndDate); date = date.AddDays((Double)Week))
{
DateTime date;
date = startDate.AddDays(i);
DateYear a = new DateYear();
switch (LimitVmodel.Day)
{
case "Saturday":
if (date.DayOfWeek == DayOfWeek.Saturday)
{
allDates.Add(a);
}
break;
case "Sunday":
if (date.DayOfWeek == DayOfWeek.Sunday)
{
allDates.Add(a);
}
break;
case "Monday":
if (date.DayOfWeek == DayOfWeek.Monday)
{
allDates.Add(a);
}
break;
}

Here is a solution with Extension.
Gets a DateTime range and a day of week.
Returns a list of DateTime.
public static class DateUtils
{
public static List<DateTime> GetWeekdayInRange(this DateTime from, DateTime to, DayOfWeek day)
{
const int daysInWeek = 7;
var result = new List<DateTime>();
var daysToAdd = ((int)day - (int)from.DayOfWeek + daysInWeek) % daysInWeek;
do
{
from = from.AddDays(daysToAdd);
result.Add(from);
daysToAdd = daysInWeek;
} while (from < to);
return result;
}
}
Usage:
namespace DatesTest
{
class Program
{
static void Main(string[] args)
{
var from = DateTime.Today; // 25/8/2019
var to = DateTime.Today.AddDays(23); // 23/9/2019
var allMondays = from.GetWeekdayInRange(to, DayOfWeek.Monday);
}
}
}
Output:
{8/26/2019 12:00:00 AM}
{9/2/2019 12:00:00 AM}
{9/9/2019 12:00:00 AM}
{9/16/2019 12:00:00 AM}
{9/23/2019 12:00:00 AM}

DateTime date = LimitVmodel.StartDate;
switch (LimitVmodel) {
case "Monday":
while (date.DayOfWeek != DayOfWeek.Monday) {
date = date.AddDays(1);
}
break;
case "Tuesday":
while (date.DayOfWeek != DayOfWeek.Tuesday) {
date = date.AddDays(1);
}
break;
//Etc...
}
AllDates.add(date);
while (DateTime.compare(date, LimitVmodel.EndDate) <= 0) {
date = date.AddDays(7);
AllDates.add(date);
}

You can use the for loop to check for the day which you are getting in LimitVmodel.Day and collate all the dates which fall on that day. Something like this:
DateTime startDate = LimitVmodel.StartDate;
DateTime endDate = LimitVmodel.EndDate;
int days = (endDate - startDate).Days;
string myDay = LimitVmodel.Day;
var myDayDayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek),myDay); //convert string to DayOfWeek type
var allDates = new List<DateTime>();
for(int i=0; i < days; i++)
{
var currDate = startDate.AddDays(i);
if(currDate.DayOfWeek == myDayDayOfWeek)
allDates.Add(currDate);
}

Related

how to get the get first Sunday of the month using date format?

Hi I need to check a condition for the first Sunday of the month for a date formatted as YYYYMMDD
var calDate = data.value; // example 20210502 is sunday
if (first Sunday of the month)
{
do this
}
else
{
do that
}
I need to check the above condition for the first Sunday of the month
Split your problem in two:
parse the string to a DateTime object
var date = DateTime.ParseExact(calDate, "yyyyMMdd", null);
Check if the DateTime object refers to the first sunday in a month. For this, it must obviously be a Sunday and the day part must be in the range 1 to 7:
var isFirstSunday = date.DayOfWeek == DayOfWeek.Sunday && date.Day <= 7;
Thsi function can return true or false if the date is first Sunday of the month or not
private static bool IsFirstSunday(DateTime date)
{
int i = 1;
while (i!=7)
{
if (date.Day==i && date.DayOfWeek == DayOfWeek.Sunday)
{
return true;
}
i++;
}
return false;
}
And use the result in your if condition
//First sunday
var date = DateTime.Parse("2021-05-02 11:27 AM");
var result = IsFirstSunday(date);
//Second sunday
date = DateTime.Parse("2021-05-09 11:27 AM");
result = IsFirstSunday(date);
//Non sunday
date = DateTime.Parse("2021-05-04 11:27 AM");
result = IsFirstSunday(date);
public static DateTime GetFirstSundayOfMonth(DateTime givenDate)
{
DateTime firstDayNextMonth = givenDate.AddDays(-givenDate.Day + 1).AddMonths(1);
int diff = 7 - (int)firstDayNextMonth.DayOfWeek;
return firstDayNextMonth.AddDays(diff);
}

How to get the list of week start date (Monday) and end date (Sunday) for the year in C#

I want to get only weeks for the whole year where I want to get the start date (Monday) and end date (Friday) in C#.
For example: 1/52 = 02 Jan (Monday) - 09 Jan (Sunday) 2/52 = 10 Jan (Monday) - 17 Jan (Sunday)
and so on.
I can get current week dates but no idea how to get for the year.
// We Set the Monday as the first day of the week.
DayOfWeek day = datetime.DayOfWeek;
int days = day - DayOfWeek.Monday;
if (days == -1)
{
days = 6; // this is when we have sunday as a DayOfWeek day
}
DateTime start = datetime.AddDays(-days);
DateTime end = start.AddDays(6);
Without making it complicated you can simply use while like below.
while (datetime.DayOfWeek != DayOfWeek.Monday)
{
datetime= datetime.AddDays(1);
}
DateTime start = datetime;
DateTime end = start.AddDays(6);
Or you want to find week from the week index 1/52 for any year then write function like below. Use it like GetWeek(1, 2020) to get 06.01.2020 - 12.01.2020. Format it as per your requirement.
public DateTime GetNextMonday(DateTime datetime)
{
return datetime.AddDays((7 - (int)datetime.DayOfWeek + (int)DayOfWeek.Monday) % 7);
}
public string GetWeek(int week, int year)
{
var start = GetNextMonday(new DateTime(year, 1, 1).AddDays((week-1)*7));
var end = start.AddDays(6);
return start.ToShortDateString() + " - " + end.ToShortDateString();
}
As far as I have understood, probably this will help, I tried the below and it displayed for me the start and end dates for the specified years:
DateTime starting = new DateTime(2020, 1, 1);
DateTime ending = new DateTime(2020, 12, 1);
DateTime currentDay = starting;
DateTime start = currentDay;
DateTime end = currentDay;
while (ending.Year >= currentDay.Year)
{
if (currentDay.DayOfWeek == DayOfWeek.Monday)
{
start = currentDay;
end = start.AddDays(6);
currentDay = end;
Console.WriteLine(start + "(" + start.DayOfWeek + ")");
Console.WriteLine(end + "(" + end.DayOfWeek + ")");
}
else
{
currentDay = currentDay.AddDays(1);
}
}
You can use methods below to calculate start day of any week of any year
public static DateTime StartOfNthWeekOfYear(int year, int weekNumber, DayOfWeek firstDayOfWeek)
{
if(weekNumber < 1)
{
throw new ArgumentOutOfRangeException(nameof(weekNumber));
}
DateTime startOfWeek = StartOfFirstWeekOfYear(year, firstDayOfWeek).AddDays((weekNumber - 1) * 7);
DateTime endOfWeek = startOfWeek.AddDays(6);
if(endOfWeek.Year != year || startOfWeek.Year != year)
{
throw new ArgumentOutOfRangeException(nameof(weekNumber));
}
return startOfWeek;
}
public static DateTime StartOfFirstWeekOfYear(int year, DayOfWeek firstDayOfWeek)
{
DateTime startOfYear = new DateTime(year, 1, 1);
if (startOfYear.DayOfWeek != firstDayOfWeek)
{
return StartOfWeek(startOfYear, firstDayOfWeek).AddDays(7);
}
return startOfYear;
}
public static DateTime StartOfWeek(DateTime value, DayOfWeek firstDayOfWeek)
{
if (value.DayOfWeek != firstDayOfWeek)
{
return value.AddDays(-((7 + (int)value.DayOfWeek - (int)firstDayOfWeek) % 7));
}
return value;
}
I think this should work for Gregorian calendars and takes into account different cultures:
public static IList<DateTime> GetFirstDayOfWeekDates(CultureInfo cultureInfo, int year)
{
var lastDateOfYear = new DateTime(year, 12, 31);
var firstDate = new DateTime(year, 1, 1);
var dayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
while (firstDate.DayOfWeek != dayOfWeek)
{
firstDate = firstDate.AddDays(1);
}
var numberOfWeeksInYear = cultureInfo.Calendar.GetWeekOfYear(lastDateOfYear, cultureInfo.DateTimeFormat.CalendarWeekRule, dayOfWeek);
var firstDayOfWeekDates = new List<DateTime>();
firstDayOfWeekDates.Add(firstDate);
var currentDate = firstDate;
for (int i = 0; i < numberOfWeeksInYear; i++)
{
var weekLater = currentDate.AddDays(7);
if (weekLater.Year == year)
{
currentDate = weekLater;
firstDayOfWeekDates.Add(currentDate);
}
}
return firstDayOfWeekDates;
}
You can test this with a console app like this (make the method static):
static void Main(string[] args)
{
var ci = new CultureInfo("en-GB");
var dates = GetFirstDayOfWeekDates(ci, DateTime.Now.Year);
foreach (var dt in dates)
{
Console.WriteLine("Date: " + dt.ToShortDateString());
}
Console.ReadLine();
}
It brings back the following:
If you want to include the end date of the week as well then you can tweak this slightly by adding a new class called WeekDate:
public class WeekDate
{
public DateTime StartOfWeek { get; set; }
public DateTime EndOfWeek { get; set; }
}
GetFirstDayOfWeekDates then becomes:
public static IList<WeekDate> GetFirstDayOfWeekDates(CultureInfo cultureInfo, int year)
{
var lastDateOfYear = new DateTime(year, 12, 31);
var firstDate = new DateTime(year, 1, 1);
var dayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
while (firstDate.DayOfWeek != dayOfWeek)
{
firstDate = firstDate.AddDays(1);
}
var numberOfWeeksInYear = cultureInfo.Calendar.GetWeekOfYear(lastDateOfYear, cultureInfo.DateTimeFormat.CalendarWeekRule, dayOfWeek);
var firstDayOfWeekDates = new List<WeekDate>();
firstDayOfWeekDates.Add(new WeekDate { StartOfWeek = firstDate, EndOfWeek = firstDate.AddDays(6) });
var currentDate = firstDate;
for (int i = 0; i < numberOfWeeksInYear; i++)
{
var weekLater = currentDate.AddDays(7);
if (weekLater.Year == year)
{
currentDate = currentDate.AddDays(7);
firstDayOfWeekDates.Add(new WeekDate { StartOfWeek = currentDate, EndOfWeek = currentDate.AddDays(6) });
}
}
return firstDayOfWeekDates;
}
Which returns:

Converting an integer to datetime and comparing the date in c#

I am having an issue in parsing two integers to datetime in C#. I have two integers as follows:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
What I want is to convert day, month and the current year to format dd/MM/yyyy and compare this date to scheduledDate which is in the format of dd/MM/yyyy. Can someone please help me with this ?
Rather than converting DateTime object to String you should always convert String to DateTime object and then compare it.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
var dtScheduledDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var dtCurrentDate = new DateTime(currentYear, month, day);
if (dtScheduledDate < dtCurrentDate)
{
// ...
}
var yourDateTime = new DateTime(currentYear, month, day);
var yourDateString = yourDateTime.ToString("dd/MM/yyyy");
// compare
If you want to compare only date then you can use Date Property of DateTime
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var dateToCompare = new DateTime(currentYear, month, day);
var scheduledDt = "25/08/2018";
var scheduledDate = DateTime.ParseExact(scheduledDt, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if(dateToCompare.Date == scheduledDate.Date)
{
//Your logic
}
POC: .Net Fiddler
Try the following, you could use DateTime.ToString() method to convert it into the format you need.
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var date = new DateTime(DateTime.Now.Year, month, day);
var formattedDate = date.ToString("dd/MM/yyyy");
var scheduledDate = "25/08/2018";
// Compare formattedDate and scheduledDate
OR
You could consider converting the scheduledDate string to date time and compare the date time objects, if that's more appropriate:
var scheduledDate = "25/08/2018";
var parsedDate = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var date = new DateTime(DateTime.Now.Year, month, day);
// compare date & parsed date
bool areEqual = date.Equals(parsedDate);
If I understand your question, just keep the proceeding zero,
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var targetDate = $"{day}/{month.ToString().PadLeft(2,'0')}/{currentYear}";
var scheduledDate = "25/08/2018";
var difference = DateTime.Compare(DateTime.Parse(targetDate),
DateTime.Parse(scheduledDate));
In case you just want to convert it to a string, this should be the easiest way:
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
// {day:D2} is equivalent to day.ToString("D2") which pads integers to a length of two
var createdDate = $"{day:D2}/{month:D2}/{currentYear}";
var scheduledDate = "25/08/2018";
EDIT
Picking up on a few things people here said, parsing both to a DateTime might be more suitable for the comparing part:
DateTime createdDateTime = new DateTime(currentYear, month, day);
DateTime scheduledDateTime = DateTime.ParseExact(scheduledDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
// Compare if it's the same day
if (createdDateTime.Date == scheduledDateTime.Date)
{
// do stuff
}
// Get the difference in Days
int dayDifference = (createdDateTime - scheduledDateTime).Days;
Alternatively .TotalDays instead of .Days returns a double
int day = 25;
int month = 08;
var currentYear = DateTime.Now.Year;
var scheduledDate = "25/08/2018";
// parse string into DateTime structure
var ci = new CultureInfo("en-UK");
var dtScheduledDate = DateTime.Parse(scheduledDate, ci);
var dtOther = new DateTime(currentYear, month, day);
if(dtOther > dtScheduledDate)
{
...
}
In this case if your variable scheduleDate is a string you can convert the other variables (day,month and currentYear) into a string in the format you want:
var dt = day + "/" + month + "/" + currentYear;
So to compare you do this:
if(dt.Equals(scheduleDate))
//Do some
else
//other thing
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
Output:
Selected Date : 10.10.2020 21:00:00
Start Date : 8.10.2020 22:00:00
End Date : 9.10.2020 22:00:00
Greater than end date!

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 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