user1594760
user1594760

Reputation: 317

List the months between two dates

I would like to know when given start and end dates, how can the months and year(s) between the two dates be retrieved.

Eg: Start Date: '1/1/2011'(mm/dd/yyyy) and End date :'11/30/2011'. The months and year to be retrieved are January,2011; February,2011; March,2011; and so on till November,2011

Upvotes: 30

Views: 42801

Answers (10)

Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

From my project:

public static List<Tuple<int, int>> GetAllMonthsBetweenDates(DateTime startDate, DateTime endDate)
{
    List<Tuple<int, int>> result = new List<Tuple<int, int>>();
    var strt = startDate;
    var end = endDate;

    while (strt.Date <= end.Date)
    {
        result.Add(new Tuple<int, int>(strt.Month, strt.Year));
        strt = strt.AddMonths(1);
    }

    return result;
}

Implementation:

private void Tests()
{
    var startDate = new DateTime(2022, 1, 1);
    var endDate = DateTime.Now;
    var a = Helpers.GetAllMonthsBetweenDates(startDate, endDate);
    foreach (var itm in a)
    {
        Debug.WriteLine(itm);
    }
}

Output:

(1, 2022)
(2, 2022)
(3, 2022)
(4, 2022)
(5, 2022)
(6, 2022)
(7, 2022)
(8, 2022)
(9, 2022)
(10, 2022)
(11, 2022)
(12, 2022)
(1, 2023)
(2, 2023)
(3, 2023)
(4, 2023)
(5, 2023)
(6, 2023)
(7, 2023)
(8, 2023)
(9, 2023)

Upvotes: 0

Mark McGookin
Mark McGookin

Reputation: 1032

for(DateTime date = fromDate; date <= toDate; date.AddMonths(1))
{
    //Do something with "date"
    //DateTime.ParseExact(date, "MM/dd/yyyy")
}

Upvotes: 3

BOB_STRONG
BOB_STRONG

Reputation: 1

        List<string> month= new List<string>();
        while (startDateValue <= endDateValue)
        {
            
            month.AddRange(new List<string>{ startDateValue.ToString("MMMM") }); 
            startDateValue = startDateValue.AddMonths(1); 
        }

Upvotes: 0

Renju Nair
Renju Nair

Reputation: 1

private HashSet<string> GetMonths(DateTime start, DateTime end)
    {
        var totalMonths = ((end.Year - start.Year) * 12) + (end.Month - start.Month) + 1;
        var diff = Enumerable.Range(0, totalMonths).Select(a => start.AddMonths(a))
                   .TakeWhile(a => a <= end)
                   .Select(a => a.ToString("MMM")).ToHashSet();

        return diff;
    }

Upvotes: 0

This function return list of months between two dates

public static IEnumerable<dynamic> MonthsBetween(
    DateTime startDate,
    DateTime endDate)
{
    DateTime iterator;
    DateTime limit;

    if (endDate > startDate)
    {
        iterator = new DateTime(startDate.Year, startDate.Month, 1);
        limit = endDate;
    }
    else
    {
        iterator = new DateTime(endDate.Year, endDate.Month, 1);
        limit = startDate;
    }

    var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
    while (iterator <= limit)
    {
        
        var firstDayOfMonth = new DateTime(iterator.Year, iterator.Month, 1);
        var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

        yield return new {
            Label = dateTimeFormat.GetMonthName(iterator.Month),
            Code = iterator.Year+"-"+iterator.Month,
            FirstDay = firstDayOfMonth,
            LastDay = lastDayOfMonth
        };

        iterator = iterator.AddMonths(1);
    }
}

Upvotes: 0

Jodrell
Jodrell

Reputation: 35716

Here we go

public static IEnumerable<(string Month, int Year)> MonthsBetween(
        DateTime startDate,
        DateTime endDate)
{
    DateTime iterator;
    DateTime limit;

    if (endDate > startDate)
    {
        iterator = new DateTime(startDate.Year, startDate.Month, 1);
        limit = endDate;
    }
    else
    {
        iterator = new DateTime(endDate.Year, endDate.Month, 1);
        limit = startDate;
    }

    var dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
    while (iterator <= limit)
    {
        yield return (
            dateTimeFormat.GetMonthName(iterator.Month), 
            iterator.Year
        );

       iterator = iterator.AddMonths(1);
    }
}

And obviously you call it like this

var startDate = DateTime.ParseExact("01/01/2011", "MM/dd/yyyy");
var endDate = DateTime.ParseExact("11/30/2011", "MM/dd/yyyy");

var months = MonthsBetween(startDate, endDate);

The results should be something like

{
    {  "January", 2011  },
    {  "February", 2011  },
    {  "March", 2011  },
    {  "April", 2011  },
    {  "May", 2011  },
    {  "June", 2011  },
    {  "July", 2011  },
    {  "August", 2011  },
    {  "September", 2011  },
    {  "October", 2011  },
    {  "November", 2011  },
}

The month names being dependent on your culture which, I think, is exactly what you asked for, right?

Upvotes: 63

Simba
Simba

Reputation: 509

You can utilize Linq by employing Enumerable.Range(startIndex, endIndex).
Example below:

    private string[] GetMonthsBetweenDates(DateTime deltaDate, int TotalMonths)
{
    var monthsBetweenDates = Enumerable.Range(0, TotalMonths)
                                       .Select(i => deltaDate.AddMonths(i))
                                       .OrderBy(e => e)
                                       .AsEnumerable();

    return monthsBetweenDates.Select(e => e.ToString("MMM")).ToArray();
}

The code above should produce the following results, assuming the current month is November.

Nov
Dec
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct

Upvotes: 0

Pankajya
Pankajya

Reputation: 119

You can use Enumerable.Range function to get the month and year between two dates,

var start = new DateTime(2011, 1, 1);
var end = new DateTime(2011, 11, 30);

var diff = Enumerable.Range(0, 13).Select(a => start.AddMonths(a))
           .TakeWhile(a => a <= end)
           .Select(a => String.Concat(a.ToString("MMMM") + ", " + a.Year));

Upvotes: 9

V4Vendetta
V4Vendetta

Reputation: 38210

You can start off with a while loop where the start date is less than or equal to the end date

Within it pull out the relevant Month and year part from the start date and store them (maybe you have a concrete class or a as a ), then increment the start date by 1 month using AddMonths(1)

//something on these lines 
while(startdate <= enddate)
{
// pull out month and year
startdate = startdate.AddMonths(1);
}

Upvotes: 33

bhuvin
bhuvin

Reputation: 1402

Use this formula :

((date1.Year - date2.Year) * 12) + date1.Month - date2.Month

And u get the number of months .

Use this in an appropriate way and you will crack it.

Welcome to Stackoverflow , Here Hardwork is your part and giving thinking lines for that is for the fraternity to do when you have a problem.

Upvotes: 4

Related Questions