w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to calculate number of months if I have starting date and elapsed number of days

Depending on your definition of months you can do just Math.Ceil(days / 30) or Math.Floor(days / 30).

You can loop adding months to from Date:

DateTime from = new DateTime(2013, 01, 15);
DateTime to = from.AddDays(395);
var months = 0;
var date = from;

while(date <= to)
{
    ++months;
    date = date.AddMonths(1);
}

A different trick is to do:

DateTime diff = DateTime.MinValue + (to - from);

// note: MinValue is 1/1/1 so we have to subtract...
var years = diff.Year - 1;
var months = diff.Month - 1;

months += years * 12;




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.