如何计算两个日期之间的月份 [英] How to calculate months between two dates

查看:181
本文介绍了如何计算两个日期之间的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有开始日期和结束日期



如何计算没有天数的天数例如



开课日期30/5/2015

结束日期2015年6月1日





在这种情况下我也要展示2月2015年5月和2015年6月



我的代码是



它计算日期之间的总天数,





i have start date and end date in my website

how to calculate no of without count of days for example

Start date 30/5/2015
End date 1/6/2015


in this case also i want to show 2 months May-2015 and june-2015

my code is

it calculate total days between dates,


protected void txtStartDate_TextChanged(object sender, EventArgs e)
   {
       string inputString = txtStartDate.Text;
       DateTime dt = DateTime.ParseExact(inputString, "yyyy/MM/dd", CultureInfo.InvariantCulture);
       dt = dt.AddMonths(Convert.ToInt32(txtNoOfMonths.Text));
       txtEndDate.Text = dt.ToString("yyyy/MM/dd");


       DateTime Date1 = Convert.ToDateTime(txtStartDate.Text);
       DateTime Date2 = Convert.ToDateTime(txtEndDate.Text);
       int DayDiff = (Date2.Date - Date1.Date).Days;
       Label1.Text = "Total days"+" "+(DayDiff.ToString());
        }





如何计算月数



how to calculate months

推荐答案

Assuming the day of the month is irrelevant (i.e. the diff between 2011.1.1 and 2010.12.31 is 1), with date1 > date2 giving a positive value and date2 > date1 a negative value

((date1.Year - date2.Year) * 12) + date1.Month - date2.Month
Or, assuming you want an approximate number of 'average months' between the two dates, the following should work for all but very huge date differences.

date1.Subtract(date2).Days / (365.25 / 12)
Note, if you were to use the latter solution then your unit tests should state the widest date range for which your application is designed to work with and validate the results of the calculation accordingly.


见这里:与年龄一起工作:它与TimeSpan不同! [ ^ ]


您可以使用LINQ来找到这个考虑以下代码:



You can use LINQ to find this consider the following code:

string StartDate="3/15/2015";
           string EndDate = "5/6/2015";
           DateTime ActualStartDate = DateTime.Parse(StartDate);
           DateTime ActualEndDate = DateTime.Parse(EndDate);
           ActualEndDate = new DateTime(ActualEndDate.Year, ActualEndDate.Month, DateTime.DaysInMonth(ActualEndDate.Year, ActualEndDate.Month));
           var diff = Enumerable.Range(0, Int32.MaxValue)
                                .Select(e => ActualStartDate.AddMonths(e))
                                .TakeWhile(e => e <= ActualEndDate)
                                .Select(e => e.ToString("MMMM"));





它输出为{March,April,May}



It gives you output as {"March","April","May"}


这篇关于如何计算两个日期之间的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆