I am writing a program in JS to find age. The parameters to a function calculateAge () are day, month, year (DOB of a person) and output should be the age of the person.
I tried the following code
let calculateAge = function(day, month, year){
var myBirthDate = new Date(calculateAge),
myBirthYear = myBirthDate.getFullYear(),
myBirthMonth = myBirthDate.getMonth(),
myBirthDay = myBirthDate.getDay()
let currentDate = new Date(),
currentYear = currentDate.getFullYear(),
currentMonth = currentDate.getMonth(),
currentDay= currentDate.getDay()
var age = currentYear - myBirthYear
var ageMonth = currentMonth - myBirthMonth
var ageDay = currentDay-myBirthDay
if (ageMonth<0 || (ageMonth == 0 && ageDay<0)){
age = parseInt(age)-1
}
}; alert (calculateAge(24,04,1993))
The output is undefined instead of 27.
My understanding is, JS does not know if the input parameters are date values. So I would like to know if there's a way to tell JS that the parameters are actually the date values (day,month,year format).
First of all, welcome to Stack Overflow!
You were close to calculating the age. You were not passing the function parameters into the Date constructor and some other minor issues such as trying to use parseInt on a value that is already an integer:
let calculateAge = function(day, month, year) {
var myBirthDate = new Date(year, month - 1, day),
myBirthYear = myBirthDate.getFullYear(),
myBirthMonth = myBirthDate.getMonth(),
myBirthDay = myBirthDate.getDay();
var currentDate = new Date(),
currentYear = currentDate.getFullYear(),
currentMonth = currentDate.getMonth(),
currentDay = currentDate.getDay();
var ageMonth = currentMonth - myBirthMonth;
var ageDay = currentDay - myBirthDay;
var age = currentYear - myBirthYear;
if (ageMonth < 0 || (ageMonth == 0 && ageDay < 0)) {
age = age - 1;
}
return age;
};
Using the experimental Temporal proposal:
const calculateAge = (day, month, year) => {
const birthday = Temporal.DateTime.from({ day, month, year });
const today = Temporal.DateTime.from(Temporal.now.date());
return today.difference(birthday, { largestUnit: 'years' }).years;
}
calculateAge(24, 4, 1993); // 27
Related
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);
}
}
This question already has an answer here:
Define prototype function with typescript
(1 answer)
Closed 4 years ago.
I'm trying to calculate start date and end date of a week from the given date range.
Below code gives me this error [ts] Property 'getWeek' does not exist on type 'Date'.
Date.prototype.getWeek = function(start)
{
start = start || 0;
var today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
var date = today.getDate() - day;
var StartDate = new Date(today.setDate(date));
var EndDate = new Date(today.setDate(date + 6));
return [StartDate, EndDate];
}
var Dates = new Date().getWeek();
You need to declare the method on the Date interface using interface merging
declare global {
interface Date {
getWeek (start?: number) : [Date, Date]
}
}
Date.prototype.getWeek = function(start)
{
start = start || 0;
var today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
var date = today.getDate() - day;
var StartDate = new Date(today.setDate(date));
var EndDate = new Date(today.setDate(date + 6));
return [StartDate, EndDate];
}
var Dates = new Date().getWeek();
Or if you are not using modules:
interface Date {
getWeek (start?: number) : [Date, Date]
}
Date is declared as a known interface by TypeScript. getWeek is not a property of Date a so it won't let you get or modify it.
You must augment the Date interface:
Add a new global.d.ts file. In it:
interface Date {
getWeek: (start: number | undefined) => [Date, Date];
}
Then, TypeScript will mix both declarations, and so it will recognise the existence of getWeek and you can define it in your code (another file, as declaration files can't contain statements)
This is because of how typescript handles extensions. You can fix your issue by modifying the interface of Date like this:
interface Date {
getWeek(start): Array<Date>;
}
Date.prototype.getWeek = function(start)
{
start = start || 0;
var today = new Date(this.setHours(0, 0, 0, 0));
var day = today.getDay() - start;
var date = today.getDate() - day;
var StartDate = new Date(today.setDate(date));
var EndDate = new Date(today.setDate(date + 6));
return [StartDate, EndDate];
}
var Dates = new Date().getWeek();
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 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
}
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));