我基本上想要的是转换Calender..SelectedDate
年龄为年,日和小时 - 在Response.Wirte()
。
如果你的生日是:19-09-1995 (DD/MM/YYYY)
它会Response.Write
Age: 18 years Days: 18*365+3 = 6573 Days Hours: 6573 * 24 = 157752
但它也必须在今年的另一个日期工作,所以如果生日是昨天
答案 0 :(得分:0)
string date = "19-09-1995";
DateTime birthday = DateTime.ParseExact(date, "d-M-yyyy", CultureInfo.InvariantCulture);
TimeSpan difference = DateTime.Now.Date - birthday;
int years = (int)difference.TotalDays / 365;
int days = (int)difference.TotalDays;
int hours = (int)difference.TotalHours;
String answer = String.Format("Age: {0} years", years);
answer += Environment.NewLine;
answer += String.Format("Days: {0}*365+{1} = {2}", years, days - years * 365, days);
answer += Environment.NewLine;
answer += String.Format("Days Hours: {0}*24 = {1}", hours / 24, hours);
但这个信息不正确,因为它不算闰年
答案 1 :(得分:0)
这段代码假设世界上没有闰年这样的东西:)
private string GetAnswer()
{
DateTime birthday = calBirthDate.SelectedDate;
TimeSpan difference = DateTime.Now.Date - birthday;
int leapYears = CountLeapYears(birthday);
int days = (int)difference.TotalDays - leapYears;
int hours = (int)difference.TotalHours - leapYears * 24;
int years = days / 365;
String answer = String.Format("Age: {0} years", years);
answer += Environment.NewLine;
answer += String.Format("Days: {0}*365+{1} = {2}", years, days - years * 365, days);
answer += Environment.NewLine;
answer += String.Format("Days Hours: {0}*24 = {1}", hours / 24, hours);
return answer;
}
private int CountLeapYears(DateTime startDate)
{
int count = 0;
for (int year = startDate.Year; year <= DateTime.Now.Year; year++)
{
if (DateTime.IsLeapYear(year))
{
DateTime february29 = new DateTime(year, 2, 29);
if (february29 >= startDate && february29 <= DateTime.Now.Date)
{
count++;
}
}
}
return count;
}