计算生日剩余的天数?

Roe*_*ler 12 c# datetime

我有一个人的生日的DateTime对象.我使用人的年,月和出生日创建此对象,方法如下:

DateTime date = new DateTime(year, month, day);
Run Code Online (Sandbox Code Playgroud)

我想知道在这个人下一个生日之前剩下多少天.在C#中这样做的最佳方法是什么(我是语言新手)?

Phi*_*ert 25

// birthday is a DateTime containing the birthday

DateTime today = DateTime.Today;
DateTime next = new DateTime(today.Year,birthday.Month,birthday.Day);

if (next < today)
    next = next.AddYears(1);

int numDays = (next - today).Days;
Run Code Online (Sandbox Code Playgroud)

如果生日是2月29日,这个简单的算法就会失败.这是另一种选择(与Seb Nilsson的答案基本相同:

DateTime today = DateTime.Today;
DateTime next = birthday.AddYears(today.Year - birthday.Year);

if (next < today)
    next = next.AddYears(1);

int numDays = (next - today).Days;
Run Code Online (Sandbox Code Playgroud)

  • 如果生日是2月29日并且当前年份不是闰年,这将失败 (2认同)
  • 这很好也很优雅,但是 2 月 29 日的处理还有一个额外的边缘情况被遗漏了。考虑以下条件:生日是 2 月 29 日,今年已经过去,今年不是闰年,但明年是。根据上述当前逻辑,计算出的“天数”将比应有的少 1,因为即使是闰年,您也会将 1 年添加到 2 月 28 日。请参阅我的答案以了解轻微的单行调整。 (2认同)

Seb*_*son 6

使用今天的年份和生日的月份和日期不适用于闰年.

经过一些测试,这就是我的工作:

private static int GetDaysUntilBirthday(DateTime birthday) {
    var nextBirthday = birthday.AddYears(DateTime.Today.Year - birthday.Year);
    if(nextBirthday < DateTime.Today) {
        nextBirthday = nextBirthday.AddYears(1);
    }
    return (nextBirthday - DateTime.Today).Days;
}
Run Code Online (Sandbox Code Playgroud)

2月29日在闰年和生日当天进行测试.