我做了一个非常简单(不准确)的程序来计算你的年龄。我想通过计算闰年并考虑到每个月有不同的天数来使其准确。有帮助吗?如何做到这一点,从哪里开始?谢谢!
using System;
public class Program
{
public static void Main()
{
float currentDay = 22;
float currentMonth = 2;
float currentYear = 2020;
Console.WriteLine("Enter your date of birth: (eg: 13/04/1998)");
Console.Write("Day: ");
int dayNum = Convert.ToInt16(Console.ReadLine());
Console.Write("Month: ");
int monthNum = Convert.ToInt16(Console.ReadLine());
Console.Write("Year: ");
int yearNum = Convert.ToInt16(Console.ReadLine());
float birthDay = (currentDay - dayNum) / 365;
float birthMonth = (currentMonth - monthNum) / 12;
float birthYear = currentYear - yearNum;
float age = birthYear + birthMonth + birthDay;
Console.WriteLine("Your age is: " + age);
}
}
发布于 2020-02-22 16:56:04
我给你的建议如下:
public static string ToAgeString(this DateTime dob)
{
DateTime today = DateTime.Today;
int months = today.Month - dob.Month;
int years = today.Year - dob.Year;
if (today.Day < dob.Day)
{
months--;
}
if (months < 0)
{
years--;
months += 12;
}
int days = (today - dob.AddMonths((years * 12) + months)).Days;
return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
years, (years == 1) ? "" : "s",
months, (months == 1) ? "" : "s",
days, (days == 1) ? "" : "s");
}
https://stackoverflow.com/questions/60349866
复制相似问题