我想每年根据用户创建帐户的日期向用户发送电子邮件.
我目前有代码检查自上次登录后是否已经过了几个月,并且想知道它是否可以修改,代码如下所示:
public static int GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
return monthDiff - 1;
}
else
{
return monthDiff;
}
}
if (GetMonthsBetween(lastLoginDate, currentDate) >= 4)
Run Code Online (Sandbox Code Playgroud)
我只想在创建日期过去一整年后发送电子邮件,我该怎么做呢?
Jon*_*eet 10
在我看来,正确的方法是改变您的设计 - 而不是要求在一个日期和另一个日期之间的月份,您应该将相关的月数添加到您的原始日期DateTime.你根本不需要一个帮助方法:
if (lastLoginDate.AddMonths(4) >= currentDate)
Run Code Online (Sandbox Code Playgroud)
或者一年:
if (lastLoginDate.AddYears(1) >= currentDate)
Run Code Online (Sandbox Code Playgroud)
.NET中没有类型表示日期,月份等"周期" - 您可能需要考虑我的Noda Time库.那时你可以:
private static readonly Period LoginExpiredPeriod = ...;
...
// Assuming lastLoginDate and currentDate are LocalDate values
if (lastLoginDate + period >= currentDate)
{
...
}
Run Code Online (Sandbox Code Playgroud)
你需要知道几个月和几年的变化长度的影响 - 例如,"2016年2月29日+ 1年"是2017年2月28日在Noda Time ...但你可能想要使用2017年3月1日,例如.基本上要小心.
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |