Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
2.67/5 (2 votes)
See more:
Dipslaying only year ... I need months and Days

C#
<script type="text/javascript">

    function CalculateAge(birthday) {

        var re = /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/;

        if (birthday.value != '') {

            if (re.test(birthday.value)) {
                birthdayDate = new Date(birthday.value);
                dateNow = new Date();

                var years = dateNow.getFullYear() - birthdayDate.getFullYear();
                var months = dateNow.getMonth() - birthdayDate.getMonth();
                var days = dateNow.getDate() - birthdayDate.getDate();
                if (isNaN(years)) {

                    document.getElementById('lblAge').innerHTML = '';
                    document.getElementById('lblError').innerHTML = 'Input date is incorrect!';
                    return false;

                }

                else {
                    document.getElementById('lblError').innerHTML = '';

                    if (months < 0 || (months == 0 && days < 0)) {
                        years = parseInt(years) - 1;
                        document.getElementById('lblAge').innerHTML = years + ' Years '
                    }
                    else {
                        document.getElementById('lblAge').innerHTML = years + ' Years '
                    }
                }
            }
            else {
                document.getElementById('lblError').innerHTML = 'Date must be mm/dd/yyyy format';
                return false;
            }
        }
    }
</script>




XML
<div>
            Date of Birth :<asp:TextBox ID="txtAge" runat="server" onblur="CalculateAge(this)" />(mm/dd/yyyy)
            <span style="color: Red">
                <asp:Label ID="lblError" runat="server"></asp:Label></span>
            <br />
            Age&nbsp;&nbsp;&nbsp; : <span id="lblAge"></span>
Posted

1 solution

for date time issues monent.js is the true friend.
here is the jsfiddle[^]



JavaScript
var startDateString = "1/7/2014";
var endDateString = "1/8/2014";

/*string to date object*/
var startDate = moment(startDateString, "DD/M/YYYY");
var endDate = moment(endDateString, "DD/M/YYYY");

/*date difference*/
var diffInDays = endDate.diff(startDate, 'days');
alert(diffInDays);

var diffInMonths = endDate.diff(startDate, 'months'); //att parm true for more better sesult
alert(diffInMonths);


var diffInYears = endDate.diff(startDate, 'years'); //att parm true for more batter sesult
alert(diffInYears);



for more http://momentjs.com/docs/#/displaying/difference/[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900