C#判断生日是否已经过去6个月

发布于 2024-08-30 18:08:56 字数 288 浏览 4 评论 0原文

如果距客户上次生日已过去 6 个月,我的应用程序需要将客户当前年龄调整 +0.5。

代码应该看起来像这样,但是 6 个月内会有多少个刻度?

if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
        {
            adjust = 0.5M;
        }
        else
        {
            adjust = 0M;
        }

提前致谢

My application needs to adjust a clients current age by +0.5 if it has been 6 months since their last birthday.

The code should look something like this, but how many ticks would there be in 6 months?

if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
        {
            adjust = 0.5M;
        }
        else
        {
            adjust = 0M;
        }

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

两个我 2024-09-06 18:08:56

编辑:你实际上知道吗?由于显然您真正需要的只是显示 6 个月以内的用户年龄,因此这才是您真正应该做的。

static decimal GetApproximateAge(DateTime dateOfBirth) {
    TimeSpan age = DateTime.Now - dateOfBirth;

    /* a note on the line below:
     * treating 182.5 days as equivalent to 6 months,
     * reasoning that this will provide acceptable accuracy
     * for ages below ~360 years
     * 
     * (result will be 1 day off for roughly every 4 years;
     * for a calculation of half-years to be inaccurate
     * would take 4 [years] * ~90 [days] = ~360)
     */

    // get age in units of 6 months
    // desired behavior is not to add 0.5 until
    // a full six months have elapsed since the user's last birthday --
    // using Math.Floor to ensure this
    double approxAgeInHalfYears = Math.Floor(age.TotalDays / 182.5);

    // now convert this to years
    // did it this way to restrict age to increments of 0.5
    double approxAgeInYears = approxAgeInHalfYears * 0.5;

    return Convert.ToDecimal(approxAgeInYears);
}

上面的代码包含一个大注释,解释了它自己的缺点,大卫指出了这一点。

现在,还有另一个选项。它有点丑陋,因为它使用了循环;但它也更加坚如磐石,因为它使用了 DateTime.AddMonths 方法,该方法的优点是已经过 Microsoft 的测试和记录。

static decimal GetApproximateAge(DateTime dateOfBirth) {
    DateTime now = DateTime.Now;

    int birthYear = dateOfBirth.Year;
    int lastYear = now.Year - 1;

    // obviously, if the user's alive, he/she had a birthday last year;
    // therefore he/she is at least this old
    int minimumAgeInYears = lastYear - birthYear;

    // now the question is: how much time has passed since then?
    double actualAgeInYears = (double)minimumAgeInYears;

    // for every six months that have elapsed since the user's birthday
    // LAST year, add 0.5 to his/her age
    DateTime birthDateLastYear = new DateTime(lastYear, 1, 1)
        .AddDays(dateOfBirth.DayOfYear);

    DateTime comparisonDate = birthDateLastYear
        .AddMonths(6);

    while (comparisonDate < now) {
        actualAgeInYears += 0.5;
        comparisonDate = comparisonDate.AddMonths(6);
    }

    return Convert.ToDecimal(actualAgeInYears);
}

人们一直建议检查dateOfBirth.AddMonths(6)的想法是错误。由于 dateOfBirth 是一个 DateTime,因此它表示用户的出生日期,而不是他们的出生日期

您要检查的是自用户的最后生日(而不是他们的出生日期)以来是否已经过去了六个月。这是一种方法:

DateTime lastBirthDay = GetLastBirthday(dateOfBirth);

if (DateTime.Today > lastBirthDay.AddMonths(6))
{
    adjust = 0.5M;
}
else
{
    adjust = 0M;
}

DateTime GetLastBirthday(DateTime dateOfBirth)
{
    int currentYear = DateTime.Now.Year;
    int birthMonth = dateOfBirth.Month;
    int birthDay = dateOfBirth.Day;

    // if user was born on Feb 29 and this year is NOT a leap year,
    // we'll say the user's birthday this year falls on Feb 28
    if (birthMonth == 2 && birthDay == 29 && !IsLeapYear(currentYear))
        birthDay = 28;

    DateTime birthdayThisYear = new DateTime(
        currentYear,
        birthMonth,
        birthDay
    );

    if (DateTime.Today > birthdayThisYear)
        return birthdayThisYear;
    else
        return birthdayThisYear.AddYears(-1);
}

bool IsLeapYear(int year) {
    return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}

EDIT: You know what, actually? Since clearly what you really need is just to display the user's age to within 6 months, this is what you should really do.

static decimal GetApproximateAge(DateTime dateOfBirth) {
    TimeSpan age = DateTime.Now - dateOfBirth;

    /* a note on the line below:
     * treating 182.5 days as equivalent to 6 months,
     * reasoning that this will provide acceptable accuracy
     * for ages below ~360 years
     * 
     * (result will be 1 day off for roughly every 4 years;
     * for a calculation of half-years to be inaccurate
     * would take 4 [years] * ~90 [days] = ~360)
     */

    // get age in units of 6 months
    // desired behavior is not to add 0.5 until
    // a full six months have elapsed since the user's last birthday --
    // using Math.Floor to ensure this
    double approxAgeInHalfYears = Math.Floor(age.TotalDays / 182.5);

    // now convert this to years
    // did it this way to restrict age to increments of 0.5
    double approxAgeInYears = approxAgeInHalfYears * 0.5;

    return Convert.ToDecimal(approxAgeInYears);
}

The above code includes a big comment explaining its own shortcomings, helpfully pointed out by David.

Now, here's yet another option. It's kind of ugly because it uses a loop; but it's also more rock-solid since it utilizes the DateTime.AddMonths method, which has the advantage of having already been tested and documented by Microsoft.

static decimal GetApproximateAge(DateTime dateOfBirth) {
    DateTime now = DateTime.Now;

    int birthYear = dateOfBirth.Year;
    int lastYear = now.Year - 1;

    // obviously, if the user's alive, he/she had a birthday last year;
    // therefore he/she is at least this old
    int minimumAgeInYears = lastYear - birthYear;

    // now the question is: how much time has passed since then?
    double actualAgeInYears = (double)minimumAgeInYears;

    // for every six months that have elapsed since the user's birthday
    // LAST year, add 0.5 to his/her age
    DateTime birthDateLastYear = new DateTime(lastYear, 1, 1)
        .AddDays(dateOfBirth.DayOfYear);

    DateTime comparisonDate = birthDateLastYear
        .AddMonths(6);

    while (comparisonDate < now) {
        actualAgeInYears += 0.5;
        comparisonDate = comparisonDate.AddMonths(6);
    }

    return Convert.ToDecimal(actualAgeInYears);
}

This idea that people have been suggesting of checking dateOfBirth.AddMonths(6) is wrong. Since dateOfBirth is a DateTime, it represents the user's birth date, not their birth day.

What you want to check is if six months have elapsed since the user's last birthday--not the date they were born. Here's one way to do that:

DateTime lastBirthDay = GetLastBirthday(dateOfBirth);

if (DateTime.Today > lastBirthDay.AddMonths(6))
{
    adjust = 0.5M;
}
else
{
    adjust = 0M;
}

DateTime GetLastBirthday(DateTime dateOfBirth)
{
    int currentYear = DateTime.Now.Year;
    int birthMonth = dateOfBirth.Month;
    int birthDay = dateOfBirth.Day;

    // if user was born on Feb 29 and this year is NOT a leap year,
    // we'll say the user's birthday this year falls on Feb 28
    if (birthMonth == 2 && birthDay == 29 && !IsLeapYear(currentYear))
        birthDay = 28;

    DateTime birthdayThisYear = new DateTime(
        currentYear,
        birthMonth,
        birthDay
    );

    if (DateTime.Today > birthdayThisYear)
        return birthdayThisYear;
    else
        return birthdayThisYear.AddYears(-1);
}

bool IsLeapYear(int year) {
    return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
欢你一世 2024-09-06 18:08:56

为什么不改为 if (dateOfBirth.Date.AddMonths(6) < DateTime.Today) 呢?

Why not if (dateOfBirth.Date.AddMonths(6) < DateTime.Today) instead?

忘羡 2024-09-06 18:08:56
        long ticks = new DateTime(0).AddMonths(6).Ticks;
        TimeSpan ts = new TimeSpan(ticks);
        long ticks = new DateTime(0).AddMonths(6).Ticks;
        TimeSpan ts = new TimeSpan(ticks);
宁愿没拥抱 2024-09-06 18:08:56
if (dateOfBirth.Date.AddMonths(6) < DateTime.Today)
{
   age += 0.5;
}
if (dateOfBirth.Date.AddMonths(6) < DateTime.Today)
{
   age += 0.5;
}
卖梦商人 2024-09-06 18:08:56

我认为你可能把事情过于复杂化了:

DateTime displayDate = User.BirthDate; // User.BirthDate is a mock for however you get the birth date

if(DateTime.Now.AddMonths(-6) > displayDate)
{
    // More than 6 Months have passed, so perform your logic to add .5 years
}

I think you might be overcomplicating things:

DateTime displayDate = User.BirthDate; // User.BirthDate is a mock for however you get the birth date

if(DateTime.Now.AddMonths(-6) > displayDate)
{
    // More than 6 Months have passed, so perform your logic to add .5 years
}
自演自醉 2024-09-06 18:08:56

像这样的东西吗?

if (DateTime.Now.AddMonths(-6) > dateofBirth.Date)
{
    dateOfBirth = dateOfBirth.AddMonths(6);
}

Something like this?

if (DateTime.Now.AddMonths(-6) > dateofBirth.Date)
{
    dateOfBirth = dateOfBirth.AddMonths(6);
}
转身泪倾城 2024-09-06 18:08:56

我想你实际上想知道距离他们上次生日是半年还是六个月(因为几个月的长度各不相同)。

    int daysDiff = DateTime.Now.DayOfYear - dayofBirth.DayOfYear;
    if (daysDiff <0) daysDiff += 365;
    double adjust = daysDiff > 365/2 ? 0.5 : 0.0;

I think you actually want to know if it is half a year since their last birthday not six months (since months vary in length).

    int daysDiff = DateTime.Now.DayOfYear - dayofBirth.DayOfYear;
    if (daysDiff <0) daysDiff += 365;
    double adjust = daysDiff > 365/2 ? 0.5 : 0.0;
初与友歌 2024-09-06 18:08:56
DateTime today = DateTime.Today;
DateTime lastBirthday = dateOfBirth.Date.AddYears(today.Year - dateOfBirth.Year);
if (lastBirthday > today) lastBirthday = lastBirthday.AddYears(-1);

if (today > lastBirthday.AddMonths(6))
    adjust = 0.5M;
else
    adjust = 0M;
DateTime today = DateTime.Today;
DateTime lastBirthday = dateOfBirth.Date.AddYears(today.Year - dateOfBirth.Year);
if (lastBirthday > today) lastBirthday = lastBirthday.AddYears(-1);

if (today > lastBirthday.AddMonths(6))
    adjust = 0.5M;
else
    adjust = 0M;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文