ageFromDOB
A utility function to calculate the age from a given date of birth (DOB) in terms of years, months, and days.> ageFromDOB(dateOfBirth: Date | string): { years: number; months: number; days: number }
- dateOfBirth: The date of birth as a `Date` object or a valid date string (e.g., `YYYY-MM-DD`).
- Returns: An object containing the age in years, months, and days.
Example
import { ageFromDOB } from "@explita/daily-toolset";
// Calculate age using a Date object
const dobDateObject = new Date("1990-05-20");
console.log(ageFromDOB(dobDateObject)); // { years: 34, months: 7, days: 21 }
// Calculate age using a date string
const dobDateString = "1990-05-20";
console.log(ageFromDOB(dobDateString)); // { years: 34, months: 7, days: 21 }
// Handle invalid date strings
const invalidDOB = "invalid-date";
try {
console.log(ageFromDOB(invalidDOB));
} catch (error) {
console.error(error.message); // "Invalid date string provided: 'invalid-date'. Expected format: YYYY-MM-DD or similar."
}
// Handle type errors
const nonDateInput = 12345;
try {
console.log(ageFromDOB(nonDateInput));
} catch (error) {
console.error(error.message); // "Expected a Date object, but received number"
}
Use Cases
- Calculating the exact age of a person for registration or profiling purposes.
- Determining eligibility based on age requirements (e.g., voting, driving, etc.).
- Tracking milestones or anniversaries for events or services.