Simple Age Calculator base on date of birth in C#
我创建了一个简单的年龄计算器。我想删除小数点,但问题是当我将
示例:我输入
有什么想法吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | static void Main(string[] args) { string year, month, day = string.Empty; Console.WriteLine("Enter your Birthdate:"); Console.WriteLine("Year :"); year = Console.ReadLine(); Console.WriteLine("Month :"); month = Console.ReadLine(); Console.WriteLine("Day :" ); day = Console.ReadLine(); try { DateTime date = Convert.ToDateTime(year +"-" + month +"-" + day); var bday = float.Parse(date.ToString("yyyy.MMdd")); var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd")); if (now < bday) { Console.WriteLine("Invalid Input of date"); Console.ReadLine(); } Console.WriteLine("Your Age is" + (String.Format("{0:00}", (now - bday)))); //it rounds off my float Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.ReadLine(); } } |
}
与评论相反,请不要在这里帮忙,因为一年不是固定的时间长度。这个转向你表达的爱是非常陌生的。你真的不应该把一个日期作为一个分数数,与第一个两个月的数字和第三和第四个几天的数字联系起来。时间不象这样工作。(Consider that the difference between 2014.0131 and 2014.0201 is much greater than the difference between 2014.0130 and 2014.0131,for example.)
最好在年月、月、日等术语中反映年龄。我的诺达时光图书馆让人觉得很简单
1 2 3 4 5 | LocalDate birthday = new LocalDate(1976, 6, 19); // For example LocalDate today = LocalDateTime.FromDateTime(DateTime.Now).Date; // See below Period period = Period.Between(birthday, today); Console.WriteLine("You are {0} years, {1} months, {2} days old", period.Years, period.Months, period.Days); |
如果你只想确定一个年份,你可以决定只使用EDOCX1[/1],或者可能根据EDOCX1[/2]回归结果。
我将建议使用
在我们的框架内,我们采用了以下方法:
ZZU1
在这里,我找到了一个答案,我用
很精确,试试看。注:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | static void Main(string[] args) { string year, month, day = string.Empty; Console.WriteLine("Enter your Birthdate:"); Console.WriteLine("Year :"); year = Console.ReadLine(); Console.WriteLine("Month :"); month = Console.ReadLine(); Console.WriteLine("Day :" ); day = Console.ReadLine(); try { DateTime date = Convert.ToDateTime(year +"-" + month +"-" + day); var bday = float.Parse(date.ToString("yyyy.MMdd")); var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd")); if (now < bday) { Console.WriteLine("Invalid Input of date"); Console.ReadLine(); } string age = (now - bday).ToString(); Console.WriteLine("Your Age is" + (age.Substring(0, age.LastIndexOf('.')))); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.ReadLine(); } } |