以Le年,天,小时,秒为单位的生存时间独立计算为Le年

时间:2018-09-08 21:48:28

标签: c# datetime logic timespan

我目前正在从事一个满足要求的学校项目,但是我想挑战自己。如何根据今天的日期/时间以以下格式准确显示我的年龄?

年龄:27年-或-天-或-小时-或-秒(占Le年)

我所做的研究:How would you calculate the age in C# using date of birth (considering leap years)

我更想寻找背后的数学原理。这是我目前正在使用的数学方法,但只能精确到16小时或960分钟或57,600秒。

// Tried using "double" datatype, still same problem.
int years = DateTime.Now.Year - dateBirthDate.Year;
int days = (years / 4) + (years * 365);
int hours = (days * 24) + DateTime.Now.Hour;
int minutes = hours * 60;
int seconds = (minutes * 60) + ((DateTime.Now.Hour * 60) * 60) + DateTime.Now.Second;

应该显示接近于0。

输出:

Thank you Mat, what is your date of birth? Feel free to include the time you were born. 09/08/2018 5:11pm
Years   :0
Days    :0
Minutes :1020
Seconds :122425

#UPDATE#1

我设法使代码部分正常工作,但是发现了另一个无法预料的问题。现在,它不会考虑尚未到来的生日。有想法吗?

//Needed casting so I could remove the decimals.
TimeSpan span = DateTime.Now.Subtract(dateBirthDate);
int years = (int)span.Days/365;
int months = years * 12;
int days = (int)span.TotalDays;
int hours = (int)span.TotalHours;
int minutes = (int)span.TotalMinutes;
int seconds = (int)span.TotalSeconds;

1 个答案:

答案 0 :(得分:1)

解决方法


必须将TimeSpan强制转换为int以删除小数。为了获取TimeSpan年,我只用了几个月,然后除以365,然后将其强制转换为(int),以便仅显示整数。然后,我创建了一个if / else条件和一个嵌套条件,以适应当前正在发生或尚未到来的生日。逻辑似乎很合理。

        //Needed casting so I could remove the decimals.
        TimeSpan span = DateTime.Now.Subtract(dateBirthDate);

        //Creating workable if/else to account for birthday's yet to come.
        int dateCorrectorMonthNow = DateTime.Now.Month;
        int dateCorrectorDayNow = DateTime.Now.Day;
        int dateCorrectorMonthThen = dateBirthDate.Month;
        int dateCorrectorDayThen = dateBirthDate.Day;


        int years = (int)span.Days/365;
        int months = years * 12;
        int days = (int)span.TotalDays;
        int hours = (int)span.TotalHours;
        int minutes = (int)span.TotalMinutes;
        int seconds = (int)span.TotalSeconds;

        if (dateCorrectorMonthNow <= dateCorrectorMonthThen)
        {
            if (dateCorrectorDayNow  <= dateCorrectorDayThen)
            {
                Console.WriteLine($"Years   :{years}");
            }
            else
            {
                Console.WriteLine($"Years   :{years-1}");
            }
        }
        else
        {
            Console.WriteLine($"Years   :{years}");
        }