Jquery get age by input value - javascript

How do I calculate the age of a user, depending on the date entered in a textbox?
I want to be able to calculate the exact age of YYYY/MM/DD, so far I've only managed to do it by year.
The code I've tried so far:
function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;
}
Any ideas?

When you set the date using this: new Date(birthYear, birthMonth, birthDay); you need to subtract 1 from the month. Months are counted from 00.
For example,
var testDate = new Date(1988,10,12) is Sat Nov 12 1988 00:00:00
You can try this alternate way:
var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
age--;
}
console.log(age);
This will return you the correct age based on input birth date.

well since i can't make comment, im gonna do it here.
first thing i would do is use momentjs for every date releated thing in js
and if i understand your right, you want something like this?
How to get difference between 2 Dates in Years, Months and days using moment.js

You can use Math.floor and the modulo operator % for integer division:
function CalculateAge() {
var dob1 = $("#txtBirthday").val();
var age1 = document.getElementById("#age");
var dateAry = dob1.value.split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var birthDate = new Date(birthYear, birthMonth, birthDay);
var currentDate = new Date();
var age = currentDate - birthDate; // don't forget the var keyword
var days = Math.floor(age / 86400000); // no need to use a string
var years = Math.floor(days / 365); // quite inaccurate actually
var remaning_days = days % 365; // use modulo operator
age1.value = years; // no need to type-cast
}

function CalculateAge() {
var dob1 = $("#txtBirthday");
var age1 = $("#age");
var dateAry = dob1.val().split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var one_day=1000*60*60*24;
var date1 = new Date(birthYear, birthMonth, birthDay);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2 = new Date();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var t = difference_ms/one_day;
age1.val(t/365);
}
if you want approx year use Math.random in result

Related

Age Reverse Calculation Using Javascript

I want to calculate age from Day,Month and Year.I already done Date Of Birth to Day,Month,Year calculation.But I want age reverse calculation
If user enter Age of :
Day:18
Month:05
Year:26
Then It will return the Original Date of Birth from current date Like DOB:10/24/1993
There are lot of example of DOB to Age(dd-mm-yyyy) but no example of Age(dd-mm-yyyy) to DOB
What is the logic of this reverse calculation in javascript?
here is the script for DOB to Age
$("#txtDob").keyup(function () {
debugger;
var mdate = $("#txtDob").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);
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 {
$("#txtAgeYY").val(year_age);
$("#txtAgeMM").val(month_age);
$("#txtAgeDD").val(day_age);
//var abc = testFunc();
}
});
but I need Age to DOB
You can create a new date that holds the current time and then subtract the current age year, month and day.
const ageYear = 26;
const ageMonth = 5;
const ageDay = 18;
const birthDay = new Date();
birthDay.setFullYear(birthDay.getFullYear() - ageYear);
birthDay.setMonth(birthDay.getMonth() - ageMonth);
birthDay.setDate(birthDay.getDate() - ageDay);
Check below javascript part will do what you want.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var ageYears = 26;
var ageMonths = 5;
var ageDays = 18;
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
var dob = new Date(year - ageYears, month - ageMonths, day - ageDays);
document.getElementById("demo").innerHTML = "DOB: " + dob;
</script>
</body>

Changing an asp:textbox text using jquery.js while trying to compute for age using (Date.now - Date) Equation

So I need to automatically compute for a person's age by javascript and show it on an asp:textbox. The birthdate is acquired by using jquery-ui's datetimepicker. I expect that I can do arithmetic functions on two date variables so I intend to calculate the age by
var age = Date.Now - $bdate;
What I have done is I converted my bdate to ISO-8601 format because I read that date.parse only works with ISO-8601 compliant format before trying to minus both dates.
Is there anything wrong to what I am thinking?
here's my code:
$('#<%= txtBDate.ClientID%>').change(function () {
var rawr = Date.parse($(#'<%= txtBDate.ClientID%>').val());
$('<%=txtAge.ClientID%>').val(Date.now - rawr);
});
So what made me solve this problem is by calling the day off and rest for the night. I guess coding for how many hours a day makes you tired and dumb.
anyways, here's the code that I made to solve this problem
$('#<%= txtBDate.ClientID%>').change(function () {
var today = new Date();
var curYear = today.getFullYear();
var curMonth = today.getMonth();
var bdate = new Date($('#<%=txtBDate.ClientID%>').val());
var bYear = bdate.getFullYear();
var bMonth = bdate.getMonth();
var age = curYear - bYear;
if (curMonth < bMonth) {
age = age - 1;
}
$('#<%=txtAge.ClientID%>').val(age);
})
function getage() {
var birthday = document.getElementById('birthdate').value // get the birthdate from the birthdate textbox with id = "birthdate"
var dob = birthday ; //insert birthrate into dob variable
var year = Number(dob.substr(0, 4)); // get year from dob variable
var month = Number(dob.substr(4, 2)) - 1; //get month from dob variable
var day = Number(dob.substr(6, 2)); //get day from dob variable
var today = new Date(); // get current date
var age = today.getFullYear() - year; // calculate age
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() <
day)) {
age--;
alert(age);
}
}

Why its not giving me the correct total month?

Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );

how to get difference in year where dates are in yyyy-mm-dd?

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.
var ds='2002-09-23';
var today_date = new Date();
alert(today_date);
Date.prototype.yyyymmdd = function() {
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
var num_years = diff_date/31536000000;
alert(num_years);
if (num_years>18){
alert (num_years);
}else{
alert ("i m not 18");
}
please help me out.
This is much shorter:
var yearsApart = new Date(new Date - new Date('2002-09-23')).getFullYear()-1970
… but be careful to take care of non UTC time zones by providing the correct datetime string!
You need no library for this, just pure javascript:
function wholeYearsBetweenTwoDates(dateOneString, dateTwoString) {
// assuming that dateTwo is later in time than dateOne
var dateOne = getDateFromString(dateOneString);
var dateTwo = getDateFromString(dateTwoString);
var result = dateTwo.getFullYear() - dateOne.getFullYear();
dateOne.setFullYear(dateTwo.getFullYear());
if (dateOne > dateTwo) {
// compensate for the case when last year is not full - e.g., when
// provided with '2009-10-10' and '2010-10-09', this will return 0
result -= 1;
}
return result;
}
function getDateFromString(stringDate) {
var dateParts = stringDate.split('-');
var result = new Date(dateParts[0], dateParts[1], dateParts[2]);
return result;
}
Try the following code to get the difference in years...
function getDateDiffInYears(date1, date2) {
var dateParts1 = date1.split('-')
, dateParts2 = date2.split('-')
, d1 = new Date(dateParts1[0], dateParts1[1]-1, dateParts1[2])
, d2 = new Date(dateParts2[0], dateParts2[1]-1, dateParts2[2])
return new Date(d2 - d1).getYear() - new Date(0).getYear() + 1;
}
var diff = getDateDiffInYears('2005-09-23', '2012-07-3');
console.log(diff); // => 7 years
Good luck!
I had been using the formula var yearsApart=milli/milliPerYear but when the day and the month are the same the rounded value is not correct.
Here you have the script I'm using right now ...
function yearDifferenceDates(firstDateDay, firstDateMonth, firstDateYear, secondDateDay, secondDateMonth, secondDateYear) {
var fisrtDate = new Date(firstDateYear, firstDateMonth - 1, firstDateDay);
var secondDate = new Date(secondDateYear, secondDateMonth - 1, secondDateDay);
if(firstDateDay == secondDateDay && (firstDateMonth - 1) == (secondDateMonth - 1)) {
return Math.round((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
return Math.floor((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
First you have to pick a JavaScript library for parsing dates using a format string (so you can provide date in the format you prefer). Try this great library (at least you do not have to care about implementation details. Date constructor and Date.parse methods must match but it's not mandatory they can parse a simple date in that format).
var date1 = getDateFromFormat("1999-10-10", "YYYY-MM-DD");
var date2 = getDateFromFormat("2012-10-10", "YYYY-MM-DD");
Then, when you have to calculate the difference:
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
var years = Math.round((date2 - date1) / millisecondsPerYear);
If you need a raw calculation you can use getFullYear() directly.
You can compare dates more easily if you convert them to their millisecond values.
var birthday = new Date('2002-09-23');
var now = new Date();
var age = now.getTime() - birthday.getTime();
if (age < (1000 * 60 * 60 * 24 * 365 * 18)) { // number of milliseconds in 18 years
document.write('not over 18');
} else {
document.write('over 18');
}
Above has a little bug but this work :)
NOT WORKING: var millisecondsPerHour = millisecondsPerMinute = 60;
WORKING FINE: var millisecondsPerHour = millisecondsPerMinute * 60;
But thx Adriano Repetti
Here the complete code (with dot Format)
var date1 = "01.01.2014";
var date2 = "31.12.2016";
var date1 = date1.split(".");
var date2 = date2.split(".");
date1 = String(date1[2] +"-"+ date1[1] +"-"+ date1[0]);
date2 = String(date2[2] +"-"+ date2[1] +"-"+ date2[0]);
var date1 = Date.parse(date1);
var date2 = Date.parse(date2);
//(Not for Europa :) )
//var date1 = Date.parse("2014-01-01");
//var date2 = Date.parse("2016-12-31");
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
// IN YEARS
var years = (date2 - date1) / millisecondsPerYear;
// IN MONTHS
var month = years * 12 // Very tricky, I know ;)
var d1=new Date(2002, 9, 23);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var yearsApart=milli/milliPerYear;
console.log(yearsApart)

How can I validate that someone is over 18 from their date of birth?

I am doing validation for Driver's Date of birth, it should be minimum of 18 from the current date.
var Dates = $get('<%=ui_txtDOB.ClientID %>');
var Split = Dates.value.split("/");
if (parseInt(Split[2]) > 1993)
{
alert("DOB year should be less than 1993");
Dates.focus();
return false;
}
I am using this above JavaScript validation for checking a person's DOB above 18, but it is not correct. I need to check with today's date and it should be above 18. How can I compare and check with the current date?
I think a better alternative would be to calculate the age of the user, and use that in your if statement.
See this SO answer on how to do just that:
Calculate age in JavaScript
Try this.
var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
var enteredAge = getAge(enteredValue.value);
if( enteredAge > 18 ) {
alert("DOB not valid");
enteredValue.focus();
return false;
}
Using this function.
function getAge(DOB) {
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Demo here: http://jsfiddle.net/codeandcloud/n33RJ/
<script>
function dobValidate(birth) {
var today = new Date();
var nowyear = today.getFullYear();
var nowmonth = today.getMonth();
var nowday = today.getDate();
var b = document.getElementById('<%=TextBox2.ClientID%>').value;
var birth = new Date(b);
var birthyear = birth.getFullYear();
var birthmonth = birth.getMonth();
var birthday = birth.getDate();
var age = nowyear - birthyear;
var age_month = nowmonth - birthmonth;
var age_day = nowday - birthday;
if (age > 100) {
alert("Age cannot be more than 100 Years.Please enter correct age")
return false;
}
if (age_month < 0 || (age_month == 0 && age_day < 0)) {
age = parseInt(age) - 1;
}
if ((age == 18 && age_month <= 0 && age_day <= 0) || age < 18) {
alert("Age should be more than 18 years.Please enter a valid Date of Birth");
return false;
}
}
</script>
After looking at various methods of doing this, I decided the simplest way was to encode the dates as 8-digit integers. You can then subtract today's code from the DOB code and check if it's greater than or equal to 180000.
function isOverEighteen(year, month, day) {
var now = parseInt(new Date().toISOString().slice(0, 10).replace(/-/g, ''));
var dob = year * 10000 + month * 100 + day * 1; // Coerces strings to integers
return now - dob > 180000;
}
let TODAY = new Date(Date.now());
let EIGHTEEN_YEARS_BACK = new Date(new Date(TODAY).getDate() + "/" + new Date(TODAY).getMonth() + "/" + (new Date(TODAY).getFullYear() - 18));
let USER_INPUT = new Date("2003/12/13");
// Validate Now
let result = EIGHTEEN_YEARS_BACK > USER_INPUT // true if over 18, false if less than 18
I think this is the closest possible way to check.
My approach is to find the date 18 (or any number) years ago from today, then see if that's after (greater) than their dob. By setting all values to date objects it makes the comparison easy.
function is_of_age(dob, age) {
// dates are all converted to date objects
var my_dob = new Date(dob);
var today = new Date();
var max_dob = new Date(today.getFullYear() - age, today.getMonth(), today.getDate());
return max_dob.getTime() > my_dob.getTime();
}
Because the Date object can parse strings in a variety of formats, You don't have to worry too much about where dob is coming from. Simply call is_of_age("1980/12/4", 18); or is_of_age("2005-04-17", 13); or basically any string format or numeric that can be parsed as a Date parameter.
My favourite approach is this one:
var dateOfBirth = new Date("02/23/1900");
// calculate difference between now and the dateOfBirth (in milliseconds)
var differenceMs = Date.now() - dateOfBirth.getTime();
// convert the calculated difference in date format
var dateFromEpoch = new Date(differenceMs);
// extract year from dateFromEpoch
var yearFromEpoch = dateFromEpoch.getUTCFullYear();
// calculate the age of the user
var age = Math.abs(yearFromEpoch - 1970);
console.log("Age of the user: " + age + " years")
You can use the below:
var birthDate = new Date("2018-06-21");
var birthDate1 = new Date("1975-06-21");
function underAgeValidate(birthday) {
const diff = Date.now() - birthday.getTime();
const ageDate = new Date(diff);
let age = Math.abs(ageDate.getUTCFullYear() - 1970);
return age < 18;
};
console.log(underAgeValidate(birthDate));
console.log(underAgeValidate(birthDate1));

Categories