Here, I have described how to get dates between two dates with an interval of days, such the dates of the last 4 weeks, and how to get the start date and end date with a range.
By this method, you can get dates between two dates with an interval of days or you can use months also. In this method, we have to pass three parameters.
- startDate :
- endDate
- intVal
- public static void getDateRange(string startDate, string endDate, int intVal)
- {
- for (DateTime date = DateTime.Parse(startDate); date <= DateTime.Parse(endDate); date = date.AddDays(intVal))
- {
- Console.WriteLine(date.ToString("yyyy-MM-dd"));
- }
- }
In the above method, we will get the dates with an interval of 2 days. Now, call the getDateRange.
- public static void Main()
- {
- getDateRange("2019-01-01", "2019-01-30", 2);
- }
Get The Date Range of the Last 4 Weeks
In this method, we have to pass one parameter, i.e., year, and get the last four-week start date and end date.
- public static void getLast4WeekRanges(int year)
- {
- int dd = int.Parse(DateTime.Now.ToString("dd"));
- int mm = int.Parse(DateTime.Now.ToString("MM"));
- string currentDayinYear = new DateTime(year, mm, dd).ToString("yyyy-MM-dd");
- DayOfWeek dDay = DateTime.Now.DayOfWeek;
- int days = dDay - DayOfWeek.Monday;
- string lastWeekDay;
- if (days == 0)
- {
- lastWeekDay = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
- }
- else
- {
- lastWeekDay = DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd");
- }
- string lastWeekEndDay = DateTime.Parse(lastWeekDay).AddDays(6).ToString("yyyy-MM-dd");
- Console.WriteLine("startdate: {0}, enddate: {1}, currentweek: {2}", lastWeekDay, lastWeekEndDay, true);
- for (int i = 0; i < 3; i++)
- {
- lastWeekDay = DateTime.Parse(lastWeekDay).AddDays(-7).ToString("yyyy-MM-dd");
- lastWeekEndDay = DateTime.Parse(lastWeekDay).AddDays(6).ToString("yyyy-MM-dd");
- Console.WriteLine("startdate: {0}, enddate: {1}, currentweek: {2}", lastWeekDay, lastWeekEndDay, false);
- }
- }

Laxmidhar SahooPosted Apr 14, 2019, 8:08 AM
A good description