I would like to use Geolocation and Date in JavaScript (ECMA) to ask the user where and when they were born and convert this into years. I am asking where they were born because I need to take into account different time zones.
So far, my function returns the number of years the user is old:
function birth() {
var their_birth_day = new Date("18 May 2005"); // Just as an example
var today = new Date();
var ms_old = today.getTime() - their_birth_day.getTime();
var yrs_old = ms_old/3.154e+10;
return yrs_old;
}
But how do I use their location to make it more accurate?
function getAge( dateString ) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Trying to validate if the user is above 16 but it is failing the condition everytime
here is my code
trying to add a condition to check if user is atleast 16 years old
if (($("#year").val(), month, day)) {
Here is the try
if (($("#year").val(), month, day) <= getAge(new Date())) {
where getAge is a function like this
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;
}
but it is still going into condition if i enter date as 10/22/2001
Your getAge function returns 16 as per your '10/22/2001' example.
But your if statement is strange. You don't need to find out someones birthdate if they were born today.
You can use:
if (getAge($("#year").val()) < 16) {
// the person is 15 or under
}
else {
// the person is 16 or over.
}
Your question and the given code is not that clear. I believe IsDate is a function to check if the input is a valid date, If yes pass that value to getAge function.
if(getAge(**enter your DOB**)>=16){
//write your code if the age is greater than or equal to 16
}
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);
}
}
I have three formats stored in database setting table.
<select>
<option value="d-m-Y">dd/mm/yyyy</option>
<option value="Y-m-d">yyyy/mm/dd</option>
<option value="m-d-Y">mm/dd/yyyy</option>
</select>
I am able to get the format value like d-m-Y or Y-m-d or m-d-Y in the line
var dateFormat = getDateFormat(); //of the below code.
function GetAge(dateString)
{
var today = new Date();
var dateFormat = getDateFormat();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
Now I want that it should check format first then calculate the age...
Please help me !!!
You are using jquery ui so before calculation use datepicker.formatDate like this.
var dateFormat = getDateFormat();// Return pattern yy-mm-dd
var today =$.datepicker.formatDate(dateFormat , new Date());;
var birthDate = $.datepicker.formatDate(dateFormat , new Date(dateString));
//Your age calculation logic
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));