0

我基本上想要的是将 Calender..SelectedDate 转换为年龄是年、日和小时 - 在Response.Wirte().

如果你的生日是:19-09-1995 (DD/MM/YYYY) 它会Response.Write

年龄:18岁
天数:18*365+3 = 6573
天时:6573 * 24 = 157752

但它也必须在今年的另一个日期工作,所以如果生日是昨天

4

2 回答 2

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

但是这个信息不是真的,因为它不计算闰年

于 2012-09-19T12:05:44.450 回答
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;
}
于 2012-09-19T13:25:24.443 回答