计算剩余生日的日子吗? [英] Calculate days remaining to a birthday?

查看:110
本文介绍了计算剩余生日的日子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个人的生日DateTime对象。我使用人的年,月,出生日期,按以下方式创建该对象:

 日期时间日期=新的日期时间(年,月,日); 



我想知道多少天是怎么这个人的下一个生日前的剩余。是什么在C#中这样做(我是新来的语言)?


解决方案

 <$的最好方式C $ C> //生日是包含生日

日期时间今天= DateTime.Today日期时间;
的DateTime下次=新日期时间(today.Year,birthday.Month,birthday.Day);

如果(下一个<今天)
下一= next.AddYears(1);

INT NUMDAYS =(下一个 - 今).Days;

如果生日是2月29日这个平凡的算法失败。这是替代(其基本上与由勒布Nilsson的答案:



 今天日期时间= DateTime.Today; 
的DateTime下次= birthday.AddYears(today.Year - birthday.Year);

如果(下一个<今天)
下一= next.AddYears(1);

INT NUMDAYS =(下一个 - 今).Days;


I have a DateTime object with a person's birthday. I created this object using the person's year, month and day of birth, in the following way:

DateTime date = new DateTime(year, month, day);

I would like to know how many days are remaining before this person's next birthday. What is the best way to do so in C# (I'm new to the language)?

解决方案

// 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;

This trivial algorithm fails if the birthday is Feb 29th. This is the alternative (which is essentially the same as the answer by 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;

这篇关于计算剩余生日的日子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆