我正在用C#开发一个兴趣计算器。我需要知道2 dates
所以,我正在计算这样的事情:
DateTime dt1 = DateTime.ParseExact(DateTime.Now.Date.ToString("dd-MM-yy"), "dd-MM-yy", CultureInfo.InvariantCulture).Date;
DateTime dt2 = DateTime.ParseExact(Duration, "dd-MM-yy", CultureInfo.InvariantCulture).Date;
Double no_days = (dt1 - dt2).TotalDays;
但是,根据月份,天数会有所不同。因此,即使天数小于30,2月15日至3月15日也构成一个月。
任何想法如何确定已过去的月数?利息计算在月末持续时间内完成。
由于
答案 0 :(得分:8)
我想不出比这更清洁的方式:
((dt1.Year - dt2.Year) * 12) + (dt1.Month - dt2.Month) - (dt1.Day < dt2.Day?1:0);
即便如此,我也不确定我是否可能错过了一些边缘案例。
答案 1 :(得分:1)
对此没有很多明确的答案,因为你总是在做假设。
此解决方案计算两个日期之间的月份,假设您想要保存当天的比较日期(意味着在计算中考虑当月的某一天)
例如,如果您的日期是2012年1月30日,那么2012年2月29日将不是一个月,而是2013年3月1日。
它经过了相当彻底的测试,可能会在我们使用它之后进行清理,但是在这里:
private static int TotalMonthDifference(DateTime dtThis, DateTime dtOther)
{
int intReturn = 0;
bool sameMonth = false;
if (dtOther.Date < dtThis.Date) //used for an error catch in program, returns -1
intReturn--;
int dayOfMonth = dtThis.Day; //captures the month of day for when it adds a month and doesn't have that many days
int daysinMonth = 0; //used to caputre how many days are in the month
while (dtOther.Date > dtThis.Date) //while Other date is still under the other
{
dtThis = dtThis.AddMonths(1); //as we loop, we just keep adding a month for testing
daysinMonth = DateTime.DaysInMonth(dtThis.Year, dtThis.Month); //grabs the days in the current tested month
if (dtThis.Day != dayOfMonth) //Example 30 Jan 2013 will go to 28 Feb when a month is added, so when it goes to march it will be 28th and not 30th
{
if (daysinMonth < dayOfMonth) // uses day in month max if can't set back to day of month
dtThis.AddDays(daysinMonth - dtThis.Day);
else
dtThis.AddDays(dayOfMonth - dtThis.Day);
}
if (((dtOther.Year == dtThis.Year) && (dtOther.Month == dtThis.Month))) //If the loop puts it in the same month and year
{
if (dtOther.Day >= dayOfMonth) //check to see if it is the same day or later to add one to month
intReturn++;
sameMonth = true; //sets this to cancel out of the normal counting of month
}
if ((!sameMonth)&&(dtOther.Date > dtThis.Date))//so as long as it didn't reach the same month (or if i started in the same month, one month ahead, add a month)
intReturn++;
}
return intReturn; //return month
}
答案 2 :(得分:0)
我最终编写了自己的例程。我希望它会帮助别人。如果有更简单的方法来计算两个日期之间的月份,请告诉我。
DateTime dt1 = DateTime.ParseExact(DateTime.Now.Date.ToString("dd-MM-yy"), "dd-MM-yy", CultureInfo.InvariantCulture).Date;
DateTime dt2 = DateTime.ParseExact(Duration, "dd-MM-yy", CultureInfo.InvariantCulture).Date;
DateTime temp = dt2;
int no_months = 0;
while ((dt1 - temp).TotalDays > 0)
{
temp = temp.AddMonths(1);
no_months++;
}
if (no_months > 0)
{
no_months = no_months - 1;
}
由于
答案 3 :(得分:0)
int MonthsElapsed = ((DateB.AddDays(1).Year - DateA.AddDays(1).Year) * 12) +
(DateB.AddDays(1).Month - DateA.AddDays(1).Month) -
(DateB.AddDays(1).Day < DateA.AddDays(1).Day ? 1 : 0);
这个公式做了一些假设:
.AddDays(1)用于计算DateB不包含触发日的月末场景。我无法想到一种更为优雅的在线方法来解释这一点。