JavaScript Age Calculator
HTML
<html>
<head>
<title>Age Calculator</title>
<link rel="stylesheet" href="style.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="main_container">
<div id="birth_date_input">
<h2 class="hedding">Select Birth Date</h2>
<input type="date" id="birth_date">
</div>
<br/>
<div id="calculate"><span>Calculate</span></div>
<div id="age_container"><span id="exact_age">Age</span></div>
</div>
</body>
</html>
CSS
#main_container {
width: 450px;
margin: 20px;
margin-left: auto;
margin-right: auto;
padding: 30px;
font-family: sans-serif;
border-radius: 5px;
border: 3px solid #999;
background: #00bfff;
}
#birth_date_input, #age_container {
text-align: center;
margin: 20px;
margin-left: auto;
margin-right: auto;
}
#age_container {
margin: 40px 5px;
padding: 20px;
border-radius: 5px;
border: 1px solid #999;
font-weight: bolder;
background: #EEE;
font-size: 20px;
line-height: 40px;
}
.hedding {
color: #fff;
text-transform: uppercase;
font-size: 27px;
font-weight: bold;
margin-bottom: 20px;
}
#age span{
color:green;
}
#calculate {
border-radius: 2px;
background-color: #0db9f2;
border: 1px solid #fff;
color: #FFFFFF;
text-align: center;
font-size: 20px;
padding: 8px 27px;
width: 200px;
transition: all 0.5s;
cursor: pointer;
margin: 0 auto;
}
#calculate span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
#calculate span:after {
content: ">";
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
#calculate:hover span {
padding-right: 25px;
}
#calculate:hover span:after {
opacity: 1;
right: 0;
}
#birth_date_input input[type="date" i] {
padding: 5px;
width: 58%;
}
JAVASCRIPT
$(document).ready(function(){
$("#calculate").click(function(){
var mdate = $("#birth_date").val().toString();
var yearThen = parseInt(mdate.substring(0,4), 10);
var monthThen = parseInt(mdate.substring(5,7), 10);
var dayThen = parseInt(mdate.substring(8,10), 10);
var today = new Date();
var birthday = new Date(yearThen, monthThen-1, dayThen);
var differenceInMilisecond = today.valueOf() - birthday.valueOf();
var year_age = Math.floor(differenceInMilisecond / 31536000000);
var day_age = Math.floor((differenceInMilisecond % 31536000000) / 86400000);
if ((today.getMonth() == birthday.getMonth()) && (today.getDate() == birthday.getDate())) {
alert("Happy B'day!!!");
}
var month_age = Math.floor(day_age/30);
day_age = day_age % 30;
if (isNaN(year_age) || isNaN(month_age) || isNaN(day_age)) {
$("#exact_age").text("Invalid birthday - Please try again!");
}
else {
$("#exact_age").html("You are<br/><div id=\"age\"><span>" + year_age + "</span> years <span>" + month_age + "</span> months <span>" + day_age + "</span> days old</div> ");
}
});
});