计算自签署之日起每年使用的服务

Calculate the annual use of a service starting from the date of signing

我需要计算从签约之日起每年使用的服务。类似于:

select Count(*) from TABLENAME where Date >= MYDATE

MYDATE 需要从订阅日期开始计算,我需要根据当前日期从订阅中获取最后一年的日期

一些示例:

subscription date: 2007-06-29

if current date is : 2015-04-29 then date is: 2014-06-29

if current date is : 2015-06-29 then date is: 2015-06-29

if current date is : 2015-06-29 then date is: 2015-06-29

我正在使用 c# 计算日期,但它在闰年时崩溃了:

var date = new DateTime(DateTime.Now.Year, subscriptionDate.Month, subscriptionDate.Day);
if (DateTime.Now.Date < date)
{
    date = date.AddYears(-1);
}

我想知道在 c# 中是否有 clever/better 方法或者 mysql 也处理闰年

---更新----

Running example with suggested solutions

使用mysqlDATE_SUB函数

DATE_SUB(Date, INTERVAL 1 YEAR)

嗯,我会在 Noda Time 做,我自己:

LocalDate subscriptionDate = ...;
LocalDate today = ...; // Need to take time zone into account
int years = Period.Between(subscriptionDate, today);
return subscription.PlusYears(years);

使用 .NET 会稍微困难一些,但我仍然会采用增加年份的方法(并让它在 2 月 29 日进行截断):

// Only call this *once* - otherwise you could get inconsistent results
DateTime today = DateTime.Today;
int years = today.Year - subscriptionDate.Year;
DateTime candidate = subscriptionDate.AddYears(years);
// We might have overshot, in which case lower the number of years.
return candidate <= today ? candidate : subscriptionDate.AddYears(years - 1);

感谢Yuri Dorokhov answer and

我找到了一个运行良好并处理闰年的解决方案:

int year = DateTime.Now.DayOfYear >= subscriptionDate.DayOfYear ? 
             DateTime.Now.Year : DateTime.Now.Year - 1;
var date = new DateTime(year, 1, 1).AddDays(subscriptionDate.DayOfYear - 1);

--------更新-----

我把这个答案留在这里作为参考,但它不能很好地处理闰年所以不要使用它