7 examples of 'javascript calculate age in years months days' in JavaScript

Every line of 'javascript calculate age in years months days' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
1function age(birthday) {
2 var ageDifMs = Date.now() - birthday.getTime();
3 var ageDate = new Date(ageDifMs);
4 return Math.abs(ageDate.getUTCFullYear() - 1970);
5}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

52export function ageAsOf(birthDate, date) {
53 if (!birthDate || !date || !birthDate.isValid() || !date.isValid()) {
54 return null;
55 }
56
57 const onOrAfterBirthday = (
58 date.month() > birthDate.month() || (
59 date.month() === birthDate.month()
60 && date.date() >= birthDate.date()
61 )
62 );
63
64 return (date.year() - birthDate.year() - (onOrAfterBirthday ? 0 : 1));
65}
44function getDaysInMonth(year, month) {
45 return 32 - new Date(UTC(year, month, 32)).getUTCDate();
46};
114export function addYears (d, years) {
115 const newDate = cloneDate(d);
116 newDate.setFullYear(d.getFullYear() + years);
117 return newDate;
118}
87function calcAges() {
88 var HOUR = 60 * 60 * 1000;
89 var DAY = HOUR * 24;
90 var WEEK = DAY * 7;
91 var MONTH = DAY * 30;
92 var YEAR = DAY * 365;
93
94 var elts = document.getElementsByTagName("time");
95 var elt;
96 for (var i = 0; elt = elts[i]; i++) {
97 elt.title = elt.textContent || elt.innerHTML;
98 var iso = elt.getAttribute("datetime");
99 var date = new Date(iso);
100 var now = new Date();
101 var diff = now.getTime() - date.getTime();
102 var str = elt.innerHTML;
103 if (diff > YEAR) str = toAge(diff / YEAR, "năm");
104 else if (diff > MONTH) str = toAge(diff / MONTH, "tháng");
105 else if (diff > WEEK) str = toAge(diff / WEEK, "tuần", true);
106 else if (diff > DAY) str = toAge(diff / DAY, "ngày", true);
107 else if (diff > HOUR) str = toAge(diff / HOUR, "tiếng", true);
108 else str = "Mới bây giờ";
109 elt.innerHTML = str;
110 }
111 }
36function daysInYear(year) {
37 return isLeapYear(year) ? 366 : 365;
38}
100function days_before_month(year, month) {
101 var post_leap_feb = month > 2 && is_leap(year);
102 return DAYS_BEFORE_MONTH[month] + (post_leap_feb ? 1 : 0);
103}

Related snippets