Say I have a timeframe defined by two DateTime
objects, d1
and d2
.
How could I know the number of times the first day of a month is in the timeframe?
Say I have a timeframe defined by two DateTime
objects, d1
and d2
.
How could I know the number of times the first day of a month is in the timeframe?
You could something like:
DateTime startDate = DateTime.Now.AddDays(-100); // {18/11/2014 4:04:07 PM}
DateTime endDate = DateTime.Now; // {26/02/2015 4:04:07 PM}
var query = Enumerable.Range(0, 1 + (endDate - startDate).Days)
.Select(i => startDate.AddDays(i))
.Where(r=> r.Day == 1);
This will first create a collection of dates from start to end, and later you can filter the results where Day
part is 1
.
For output:
foreach (var dateTime in query)
{
Console.WriteLine(dateTime);
}
Output:
01/12/2014 4:04:07 PM
01/01/2015 4:04:07 PM
01/02/2015 4:04:07 PM
Another approach without the previous bruit force....
DateTime startDate = new DateTime(2014, 09, 01);
DateTime endDate = new DateTime(2015, 02, 02);
DateTime loopDate = startDate;
var totalMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
if (startDate.Day != 1)
{
loopDate = new DateTime(startDate.Year, startDate.Month, 1).AddMonths(1);
}
List<DateTime> firstDayOfMonth = Enumerable.Range(0, totalMonths)
.Select(i => loopDate.AddMonths(i))
.ToList();
firstDayOfMonth.Add(new DateTime(endDate.Year,endDate.Month, 1));
This calculates the months difference based on solution provided here. Later it checks if the startDate
is the first day of month then ignore it, and creates a loopDate
which would be next available first day of month, and continues till endDate
.
Here is a working .Net fiddle
This is simple math.
D1: Jan 23rd 2015 D2: Mar 2nd 2015
Find the number of months that have passed (d2.Month - d1.Month).
That gives you the number of first of the months that have passed.
Edge cases you will need to consider:
D1 and D2 year is different - this is simple as well:
2.1. Calculate months between D1 and the end of its year (IE: D1 to
Dec 31st), then make sure to check edge case 1.
2.2. Calculate the months between D2 and the start of its year (IE: Jan 1st to D2)
2.3. After that, add 12 for every year difference greater than 1 (it means more than one year has passed - D1 is 2010 and D2 is 2013 - 2 whole years have passed. Step one caclulated the months in 2010, and step 2 for 2013.
2.4. Add the results of steps 1,2, and 3 together.