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

标签 c# mysql date datetime

我需要计算从签约之日起每年使用的服务。像这样的东西:

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# 或 mysql 中是否有更聪明/更好的方法来处理闰年

---更新----

Running example with suggested solutions

最佳答案

好吧,我会在 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);

关于c# - 计算自签署之日起每年使用的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28483049/

相关文章:

c# - 使用静态构造函数时 Visual Studio 的智能感知中断

mysql - 为重建 Mysql 索引安排一个每周脚本

mysql - 来自 SELECT 语句的 SQL UPDATE 语句?

php - 关联数据库中不同表的两个元素

python - 在 Python/Django 中反序列化 JSON 日期字段

mysql - 如何获取所选组的最新N条记录

c# - 如何从 bin 文件夹中删除 *.compiled 文件?

c# - 与 ContentTemplate 中的 Bindings 和 DataContext 混淆

c# - 由于 VS 在 ChromeDriver 上持有锁,无法在 Visual Studio 2013 中运行顺序 Selenium 测试

Python date.today 显示第二天