Quantcast
Channel: Difference in months between two dates - Stack Overflow
Viewing all articles
Browse latest Browse all 46

Answer by phil123456 for Difference in months between two dates

$
0
0

Insane method that counts all days, so super precise

helper class :

public class DaysInMonth{    public int Days { get; set; }    public int Month { get; set; }    public int Year { get; set; }    public bool Full { get; set; }}

function:

    public static List<DaysInMonth> MonthsDelta(DateTime start, DateTime end)    {        var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)          .Select(offset => start.AddDays(offset))          .ToArray();        DateTime? prev = null;        int days = 0;        List < DaysInMonth > list = new List<DaysInMonth>();        foreach (DateTime date in dates)        {            if (prev != null)            {                if(date.Month!=prev.GetValueOrDefault().Month)                {                    DaysInMonth daysInMonth = new DaysInMonth();                    daysInMonth.Days = days;                    daysInMonth.Month = prev.GetValueOrDefault().Month;                    daysInMonth.Year = prev.GetValueOrDefault().Year;                    daysInMonth.Full = DateTime.DaysInMonth(daysInMonth.Year, daysInMonth.Month) == daysInMonth.Days;                    list.Add(daysInMonth);                    days = 0;                }            }            days++;            prev = date;        }        //------------------ add last        if (days > 0)        {            DaysInMonth daysInMonth = new DaysInMonth();            daysInMonth.Days = days;            daysInMonth.Month = prev.GetValueOrDefault().Month;            daysInMonth.Year = prev.GetValueOrDefault().Year;            daysInMonth.Full = DateTime.DaysInMonth(daysInMonth.Year, daysInMonth.Month) == daysInMonth.Days;            list.Add(daysInMonth);        }        return list;    }

Viewing all articles
Browse latest Browse all 46

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>