how to code a check age function in javascript
function Person(dob) {
// [1] new Date(dateString)
this.birthday = new Date(dob); // transform birthday in date-object
this.calculateAge = function() {
// diff = now (in ms) - birthday (in ms)
// diff = age in ms
const diff = Date.now() - this.birthday.getTime();
// [2] new Date(value); -> value = ms since 1970
// = do as if person was born in 1970
// this works cause we are interested in age, not a year
const ageDate = new Date(diff);
// check: 1989 = 1970 + 19
console.log(ageDate.getUTCFullYear()); // 1989
// age = year if person was born in 1970 (= 1989) - 1970 = 19
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
}
var age =new Person('2000-1-1').calculateAge();
console.log(age); // 19
Also in JavaScript:
- remove element json javascript
- ERROR in ./node_modules/tns-core-modules/ui/core/view/view.js Module not found: Error: Can't resolve '@nativescript/core/ui/core/view/view' in '/home/deepali/projects/supersquad-client/node_modules/tns-core-modules/ui/core/view'
- how to scroll down to the bottom of a div using javascript
- javascript date double digit month
- get selected text js
- js only first 50 letters
- angular vs react vs vue
- javascript innertext vs innerhtml
- javascript use variable regex
- javascript foreach in object
- javascript how to check if image exists
- javascript filter array of objects
- boton de copiar en html y js
- bash parse json
- jquery dialog button text set by variable
- arrow function javascript
- javascript array get nth element
- jquery to hide a div
- get random element from array js
- reverse proxy using expressjs
- multiple case switch javascript
- testing library react hooks
- int to string javascript
- angularjs