如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
如何在c#中计算两个日期之间的月差?
c#中是否有相当于VB的DateDiff()方法。我需要找出相隔数年的两个日期之间的月差。文档说我可以像这样使用TimeSpan:
TimeSpan ts = date1 - date2;
但这里的数据是以天为单位的。我不想把这个数字除以30,因为不是每个月都是30天,而且两个操作数的值相差很大,所以我担心除以30可能会得到错误的值。
有什么建议吗?
当前回答
一定是有人干的))
扩展方法返回给定日期之间的完整月数。无论以什么顺序接收日期,都会返回一个自然数。在“正确”答案中没有近似的计算。
/// <summary>
/// Returns the difference between dates in months.
/// </summary>
/// <param name="current">First considered date.</param>
/// <param name="another">Second considered date.</param>
/// <returns>The number of full months between the given dates.</returns>
public static int DifferenceInMonths(this DateTime current, DateTime another)
{
DateTime previous, next;
if (current > another)
{
previous = another;
next = current;
}
else
{
previous = current;
next = another;
}
return
(next.Year - previous.Year) * 12 // multiply the difference in years by 12 months
+ next.Month - previous.Month // add difference in months
+ (previous.Day <= next.Day ? 0 : -1); // if the day of the next date has not reached the day of the previous one, then the last month has not yet ended
}
但如果你仍然想要得到月份的小数部分,你只需要在回报中再加一项:
+(下一个。Day - previous.Day) / DateTime.DaysInMonth(previous. Day)年,previous.Month)
其他回答
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = new DateDifference(Convert.ToDateTime("2018-09-13"), Convert.ToDateTime("2018-11-15")).ToString();
label2.Text = new DateDifference(Convert.ToDateTime("2018-10-12"), Convert.ToDateTime("2018-11-15")).ToString();
DateDifference oDateDifference = new DateDifference(Convert.ToDateTime("2018-11-12"));
label1.Text = oDateDifference.ToString();
}
}
public class DateDifference
{
public DateTime start { get; set; }
public DateTime currentDAte { get; set; }
public DateTime origstart { get; set; }
public DateTime origCurrentDAte { get; set; }
int days { get; set; }
int months { get; set; }
int years { get; set; }
public DateDifference(DateTime postedDate, DateTime currentDAte)
{
this.start = this.removeTime(postedDate);
this.currentDAte = this.removeTime(currentDAte);
this.origstart = postedDate;
this.origCurrentDAte = currentDAte;
}
public DateDifference(DateTime postedDate)
{
DateTime currentDate_ = DateTime.Now;
this.start = this.removeTime(postedDate);
this.currentDAte = this.removeTime(currentDate_);
this.origstart = postedDate;
this.origCurrentDAte = currentDate_;
if (start > this.currentDAte)
{
throw new Exception("Current date is greater than date posted");
}
this.compute();
}
void compute()
{
while (this.start.Year <= this.currentDAte.Year)
{
if (this.start.Year <= this.currentDAte.Year && (this.start.AddMonths(1) <= this.currentDAte))
{
++this.months;
this.start = this.start.AddMonths(1);
}
if ((this.start.Year == this.currentDAte.Year) && (this.start >= this.currentDAte.AddMonths(-1) && this.start <= this.currentDAte))
{
break;
}
}
while (this.start.DayOfYear < this.currentDAte.DayOfYear)
{
++this.days;
this.start = start.AddDays(1);
}
if (this.months > 11)
{
while (this.months > 11)
{
++this.years;
this.months = months - 12;
}
}
}
public override string ToString()
{
if (this.start > this.currentDAte)
{
throw new Exception("Current date is greater than date posted");
}
String ret = this.ComposeTostring();
this.reset();
return ret;
}
private String ComposeTostring()
{
this.compute();
if (this.years > 0)
{
if (this.months > 0)
{
if (this.days > 0)
{
return String.Format("{0} year{1}, {2} month{3} && {4} Day{5} ago", this.years, plural(this.years), this.months, plural(this.months), this.days, plural(this.days));
}
return String.Format("{0} year{1}, {2} month{3} ago", this.years, plural(this.years), this.months, plural(this.months));
}
else
{
if (this.days > 0)
{
return String.Format("{0} year{1},{2} day{3} ago", this.years, plural(this.years), this.days, plural(this.days));
}
return String.Format("{0} year{1} ago", this.years, plural(this.years));
}
}
if (this.months > 0)
{
if (this.days > 0)
{
return String.Format("{0} month{1}, {2} day{3} ago", this.months, plural(this.months), this.days, plural(this.days));
}
else
{
return String.Format("{0} month{1} ago", this.months, plural(this.months));
}
}
if ((this.origCurrentDAte - this.origstart).Days > 0)
{
int daysDiff = (this.origCurrentDAte - this.origstart).Days;
this.origstart = this.origstart.AddDays(daysDiff);
int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
return String.Format("{0} day{1}, {2} hour{3} ago", daysDiff, plural(daysDiff), HoursDiff, plural(HoursDiff));
}
else if ((this.origCurrentDAte - this.origstart).Hours > 0)
{
int HoursDiff = (this.origCurrentDAte - this.origstart).Hours;
this.origstart = this.origstart.AddHours(HoursDiff);
int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
return String.Format("{0} hour{1}, {2} minute{3} ago", HoursDiff, plural(HoursDiff), MinDiff, plural(MinDiff));
}
else if ((this.origCurrentDAte - this.origstart).Minutes > 0)
{
int MinDiff = (this.origCurrentDAte - this.origstart).Minutes;
this.origstart = this.origstart.AddMinutes(MinDiff);
int SecDiff = (this.origCurrentDAte - this.origstart).Seconds;
return String.Format("{0} minute{1}, {2} second{3} ago", MinDiff, plural(MinDiff), SecDiff, plural(SecDiff));
}
else if ((this.origCurrentDAte - this.origstart).Seconds > 0)
{
int sec = (this.origCurrentDAte - this.origstart).Seconds;
return String.Format("{0} second{1}", sec, plural(sec));
}
return "";
}
String plural(int val)
{
return (val > 1 ? "s" : String.Empty);
}
DateTime removeTime(DateTime dtime)
{
dtime = dtime.AddHours(-dtime.Hour);
dtime = dtime.AddMinutes(-dtime.Minute);
dtime = dtime.AddSeconds(-dtime.Second);
return dtime;
}
public void reset()
{
this.days = 0;
this.months = 0;
this.years = 0;
this.start = DateTime.MinValue;
this.currentDAte = DateTime.MinValue;
this.origstart = DateTime.MinValue;
this.origCurrentDAte = DateTime.MinValue;
}
}
你可以这样做
if ( date1.AddMonths(x) > date2 )
这个简单的静态函数计算两个Datetimes之间的月份分数。
1.1. 到31.1。= 1.0 1.4. 到15.4。= 0.5 16.4. 到30.4。= 0.5 1.3. 到1.4。= 1 + 1/30
该函数假设第一个日期比第二个日期小。要处理负时间间隔,可以通过在开始时引入符号和变量交换来轻松地修改函数。
public static double GetDeltaMonths(DateTime t0, DateTime t1)
{
DateTime t = t0;
double months = 0;
while(t<=t1)
{
int daysInMonth = DateTime.DaysInMonth(t.Year, t.Month);
DateTime endOfMonth = new DateTime(t.Year, t.Month, daysInMonth);
int cutDay = endOfMonth <= t1 ? daysInMonth : t1.Day;
months += (cutDay - t.Day + 1) / (double) daysInMonth;
t = new DateTime(t.Year, t.Month, 1).AddMonths(1);
}
return Math.Round(months,2);
}
除了所有给出的答案,我发现这段代码非常简单。DateTime。MinValue是1/1/1,我们必须从月,年和日减去1。
var timespan = endDate.Subtract(startDate);
var tempdate = DateTime.MinValue + timespan;
var totalMonths = (tempdate.Year - 1) * 12 + tempdate.Month - 1;
var totalDays = tempdate.Day - 1;
if (totalDays > 0)
{
totalMonths = totalMonths + 1;
}
如果你只关心月份和年份,想要触及两个日期(例如你想要从JAN/2021到AGO/2022),你可以使用这个:
int numberOfMonths= (Year2 > Year1 ? ( Year2 - Year1 - 1) * 12 + (12 - Month1) + Month2 + 1 : Month2 - Month1 + 1);
例子:
Year1/Month1: 2021/10
Year2/Month2: 2022/08
numberOfMonths = 11;
或者同年:
Year1/Month1: 2021/10
Year2/Month2: 2021/12
numberOfMonths = 3;
如果你只想触碰其中一个,就去掉两个+ 1。