Age Reverse Calculation Using Javascript - 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>

Related

Jquery get age by input value

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

i am using datetime picker and want that my start and end date must have difference of 24 hours

Start time is :- 02/18/2014 11:00
End time is :-02/27/2014 09:33
I want to calculate the difference between 2 dates using jquery
so that I can add validation that user must keep the difference of 24 hour (1day) while selecting the date.
this is the jquery
var start = new Date("2014-02-18");
var end = new Date();
var diff = new Date(end - start);
var days = diff/1000/60/60/24
//alert(days);
if(days<=1){
alert("less then 1 day");
}
else{
alert("more then 1 day");
}
this is the jsfiddle for it
http://jsfiddle.net/3QAJa/5/
var start_actual_time = "02/18/2014 11:00";
var end_actual_time = "02/27/2014 09:33";
start_actual_time = new Date(start_actual_time);
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time - start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
alert(formatted);

Validate date for anyone over 18 with jQuery

I have a form on my site that should validate for anyone who is over 18.
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
var output = currdate - mydate
if ((currdate - mydate) > 0){
// you are not 18
}
But it working totally opposite way. I would like the if statement to take action when user is over under 18 years old.
Thank you for your help in advance
check this DEMO
var day = 12;
var month = 12;
var year = 2006;
var age = 18;
var setDate = new Date(year + age, month - 1, day);
var currdate = new Date();
if (currdate >= setDate) {
// you are above 18
alert("above 18");
} else {
alert("below 18");
}
var day = $("#dobDay").val();
var month = $("#dobMonth").val();
var year = $("#dobYear").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if(currdate < mydate)
{
alert('You must be at least 18 years of age.');
}
Here is a somewhat lighter version that I tested:
var day = 1;
var month = 1;
var year = 1999;
var age = 18;
var cutOffDate = new Date(year + age, month, day);
if (cutOffDate > Date.now()) {
$('output').val("Get Outta Here!");
} else {
$('output').val("Works for me!");
}
The key is to add the minimum age to the birthdate and confirm that it is before the current date. You are checking if the current date minus the minimum age (basically the latest birthdate allowed) was greater than than the birthdate provided, which will give you the reverse.
18 year old validation rule for jQuery Validator plugin using addMethod function.
jQuery.validator.addMethod(
"validDOB",
function(value, element) {
var from = value.split(" "); // DD MM YYYY
// var from = value.split("/"); // DD/MM/YYYY
var day = from[0];
var month = from[1];
var year = from[2];
var age = 18;
var mydate = new Date();
mydate.setFullYear(year, month-1, day);
var currdate = new Date();
var setDate = new Date();
setDate.setFullYear(mydate.getFullYear() + age, month-1, day);
if ((currdate - setDate) > 0){
return true;
}else{
return false;
}
},
"Sorry, you must be 18 years of age to apply"
);
and
$('#myForm')
.validate({
rules : {
myDOB : {
validDOB : true
}
}
});
if it's working the opposite way have you tried swapping the > for a < on the second to last line?
I think it will be easier to understand if we rename the variables
mydate => givenDate
currdate => thresholdDate
if givenDate > thresholdDate => you are not 18
else => you are 18
i.e.
if ( givenDate > thresholdDate ){
// you are not 18
}
i.e
if ((givenDate - thresholdDate) > 0){
// you are not 18
}
i.e.
if ((mydate - currdate ) > 0){
// you are not 18
}

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