age2
v1.0.2
Published
🎂 Lightweight and documented age object for converting date of birth to age
Downloads
101
Maintainers
Readme
Quality Package Template
Light and fully documented Age object for TS and JS
📦 Installation
- Using
npm
npm i age2
- Using
Yarn
yarn add age2
- Using
pnpm
pnpm add age2
⚙️ Usage
How to import
- ES Modules
import { Age } from "age2";
- Common JS
const { Age } = require("age2");
How to construct
Age constructor is exactly the same as Date
's
Cause age is determined by underlying date.
Ways to construct
- Date string
const age = new Age("1970-01-01 11:25:04");
- Milliseconds since 1st of jan. 1970
const age = new Age(19504000);
- By passing a date object
const age = new Age(new Date("1970-01-01 11:25:04"));
- By passing each date part separately
const age = new Age( 1970, // year 0, // month (january) 0, // Optional: day of the mons 0, // Optional: hours 0, // Optional: minutes 0, // Optional: seconds 0 // Optional: milliseconds );
Properties
value
console.log(age.value); // 52
dateOfBirth
console.log(age.dateOfBirth.toISOString()); // "1970-01-01T08:25:04.000Z"
dayOfBirth
console.log(age.dateOfBirth.toISOString()); // "1970-01-01T00:00:00.000Z"
isBirthday(date?)
console.log(age.isBirthday(/* default: now */)); // false console.log(age.isBirthday("2021-01-01")); // true console.log(age.isBirthday("2021-01-02")); // false
Serialization
Date object serializes as a number
console.log(age.value); // 52
console.log(age.valueOf); // 52
console.log(+age); // 52
console.log(String(age)); // 52
console.log(JSON.stringify(age)); // 52