Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算下一个生日的月份、天数_C#_Date - Fatal编程技术网

C# 计算下一个生日的月份、天数

C# 计算下一个生日的月份、天数,c#,date,C#,Date,我有一个代码,我可以找到唯一的天数计数下一个生日,但我想不仅天,而且月 DateTime birthday=dtp.Value; DateTime td = DateTime.Today; DateTime next = new DateTime(td.Year, birthday.Month, birthday.Day); if (next < td) { next = next.A

我有一个代码,我可以找到唯一的天数计数下一个生日,但我想不仅天,而且月

        DateTime birthday=dtp.Value;
        DateTime td = DateTime.Today;
        DateTime next = new DateTime(td.Year, birthday.Month, birthday.Day);

        if (next < td)
        {
            next = next.AddYears(1);
        }

        int d = (next - td).Days;`
DateTime生日=dtp.Value;
DateTime td=DateTime.Today;
DateTime next=新日期时间(td.Year,birth.Month,birth.Day);
如果(下一个
如果我的生日是1994年10月29日,而不是int d,我将得到44天(剩余天数),但我想要1个月14天作为输出

请帮我解决这个问题

试试这个:

int months = 0;
for (; months< 12; )
{
    td = td.AddMonths(1);
    if (td > next)
    {
        td = td.AddMonths(-1);
        break;
    }
    months++;
}
int-months=0;
(月<12;)
{
td=td.add月数(1);
如果(td>next)
{
td=td.AddMonths(-1);
打破
}
月++;
}
在“int d…”行之前插入。它应该给你月数,你的日计算应该是<1个月。

问题是,“一个月”不是“一个月”,而是28到31之间的天数

但是,通过应用
AddMonths
,您可以非常接近一种统一且有用的方法:

DateTime birthday = new DateTime(1980, 11, 19);
DateTime today = DateTime.Today;
int months = 0;
int days = 0;

DateTime nextBirthday = birthday.AddYears(today.Year - birthday.Year);
if (nextBirthday < today)
{
    nextBirthday = nextBirthday.AddYears(1);
}

while (today.AddMonths(months + 1) <= nextBirthday)
{
    months++;
}
days = nextBirthday.Subtract(today.AddMonths(months)).Days;

Console.WriteLine("Next birthday is in {0} month(s) and {1} day(s).", months, days);

可能重复的So,您会考虑将30天作为1个月吗?好的,谢谢我会检查可能重复的So,请注意,您必须使用所示的
AddYears
,以获得下一个生日的精确计算。
Next birthday is in 2 month(s) and 4 day(s).