Created
September 9, 2020 11:56
-
-
Save waqaskhan540/b748cda6b1c4275552ff335d8b8ac1cb to your computer and use it in GitHub Desktop.
Start and end dates for N previous months
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
internal class DateRange | |
{ | |
public DateTime StartDate { get; set; } | |
public DateTime EndDate { get; set; } | |
} | |
static void Main(string[] args) | |
{ | |
var list_of_dates = new List<DateRange>(); | |
const int MAX_PREVIOUS_MONTHS = 18; | |
var today = DateTime.UtcNow; | |
var current_month_first_day = new DateTime(today.Year, today.Month, 1); | |
list_of_dates.Add(new DateRange { StartDate = current_month_first_day, EndDate = today }); | |
int counter = 0; | |
while (counter < MAX_PREVIOUS_MONTHS) | |
{ | |
var last_month_last_day = current_month_first_day.AddDays(-1); | |
var last_month_first_day = new DateTime(last_month_last_day.Year, last_month_last_day.Month, 1); | |
list_of_dates.Add(new DateRange { StartDate = last_month_first_day, EndDate = last_month_last_day }); | |
current_month_first_day = last_month_first_day; | |
counter++; | |
} | |
PrintDates(list_of_dates); | |
Console.ReadLine(); | |
} | |
private static void PrintDates(List<DateRange> list_of_dates) | |
{ | |
foreach (var date in list_of_dates) | |
Console.WriteLine($"from = {date.StartDate} to = {date.EndDate}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment