Asp.net Get the difference between 2 date in Month and with decimal value for the day left
Is there a way to get the difference between two dates in Month. I would like decimal for the day.
EX :
First Date : 2010-12-20
Second Date : 2011-12-30
This is like 1 months and 10 days between these date.
The difference should give me : 1.33
DateTime dt = new DateTime();
dt = Convert.ToDateTime("2011-12-30"); ;
DateTime dt2 = new DateTime();
dt开发者_运维问答2 = Convert.ToDateTime("2010-12-20");
int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(dt,dt2);
You will need to work out the number of whole months first. Then add the days as a fraction of days in a month. If we work with 30 days in a month, it might be:
int wholeMonthsDiff = ((date2.Year * 12) + date2.Month) - ((date1.Year * 12) + date1.Month);
if (date2.Day < date1.Day)
wholeMonthsDiff--;
var diff = date2 - date1.AddMonths(wholeMonthsDiff);
double monthsDifference = wholeMonthsDiff + (diff.Days / 30d);
You could use DateDiff from VisualBasic-Namespace(also when using C#):
VB.Net
Dim monthsTotal As Double = DateDiff("m", dt, dt2) + _
(dt2.Day - dt.Day) / DateDiff("d", dt2, DateAdd("m", 1, dt2))
C#
double monthsTotal = DateAndTime.DateDiff("m", dt, dt2) + (dt2.Day - dt.Day) / DateAndTime.DateDiff("d", dt2, DateAndTime.DateAdd("m", 1, dt2));
Btw, the difference of your example dates is 1 year and 10 days not 1 month and 10 days.
精彩评论