如何计算年龄 [英] how to calculate age

查看:105
本文介绍了如何计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

textbox1.text- DOB,格式为dd / mm / yyyy by user

如何计算年龄

textbox1.text- DOB in format dd/mm/yyyy by user
how to calcualte age in years

推荐答案

有一个看这里:与年龄合作:这不是与TimeSpan相同! [ ^ ]
Have a look here: Working with Age: it's not the same as a TimeSpan![^]


嘿我不是专家但是尝试这段代码可能过于冗长而且可能有很多if-nested -if循环,但我认为即使是初学者也能快速理解这段代码



首先我正在使用此代码接受一个文本框中的出生日期文本并显示年龄一旦出生日期消失,就在另一个文本框上



让我们将出生日期必须输入的文本框输入为txtDateofBirth,并将年龄显示为txtAge

所以我们必须显示年龄文本在txtDateofBirth中更改





hey i am not an expert but try this code maybe its too lengthy and may have lots of if-nested-if loops but i think even a beginner can understand this code quickly

first i am doing this code to accept a text of date of birth in one textbox and display age on another textbox as soon as the date of birth is enetered

lets take the textbox which date of birth has to be entered as txtDateofBirth and that to display age as txtAge
so we have to display age when text is changed in txtDateofBirth


protected void txtDateofBirth_TextChanged1(object sender, EventArgs e)
    {
        DateTime dob = Convert.ToDateTime(txtDateofBirth.Text); //convert the inputtext to date format ie of dd/mm/yyy
        int myYear = dob.Year;//getting year of date of birth
        int myMonth = dob.Month;//getting month of date of birth
        int myDay = dob.Day;//getting day of date of birth
        int currentYear = DateTime.Now.Year;//getting current year
        int currentMonth = DateTime.Now.Month;//getting current month
        int currentDay = DateTime.Now.Day;//getting current day
        int Age = currentYear - myYear;//calculating age in a general approach
        if (currentMonth >= myMonth)
        {
            if (currentMonth == myMonth)
            {
                if (currentDay > myDay)
                {
                    txtAge.Text = Convert.ToString(Age);
                }
                else
                {
                    txtAge.Text = Convert.ToString(Age - 1);
                }
            }


            else
            {
                txtAge.Text=Convert.ToString(Age);
            }

            }
        else
        {
            txtAge.Text=Convert.ToString(Age-1);
        }
        }
    }



所以你必须启用txtDateofBirth的autopostback才能快速获得年龄

这是我的第一个解决方案,如果它太长则很抱歉


so you must enable autopostback of txtDateofBirth To get the age quickly
this is my first solution so sorry if it is too lengthy


这篇关于如何计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆