gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:02:30 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com