0.3.2 • Published 7 months ago

date-differencer v0.3.2

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

date-differencer

CI

Calculate the time interval between two Date objects and output the result in years plus months plus days plus hours plus minutes plus seconds plus milliseconds (instead of representing the same duration in different units). This library is useful for lifespan check and age calculation.

Usage

import {
    dateDiff, dateTimeDiff, dayDiff, dayTimeDiff,
    addDateTimeDiff, addDayTimeDiff
} from "date-differencer";

const a = new Date(2022, 5, 6, 0);
const b = new Date(2023, 7, 9, 1);

console.log(dateDiff(a, b));
/*
{
    "years": 1,
    "months": 2,
    "days": 3
}
*/

console.log(dateTimeDiff(a, b));
/*
{
    "years": 1,
    "months": 2,
    "days": 3,
    "hours": 1,
    "minutes": 0,
    "seconds": 0,
    "milliseconds": 0
}
*/

console.log(Math.trunc(dayDiff(a, b))); // (365 + 31 + 30 + 3) = 429

console.log(dayTimeDiff(a, b));
/*
{
    "days": 429,
    "hours": 1,
    "minutes": 0,
    "seconds": 0,
    "milliseconds": 0
}
*/

console.log(addDateTimeDiff(a, dateTimeDiff(a, b))); // the same as b
console.log(addDayTimeDiff(a, dayTimeDiff(a, b)));   // the same as b

This library can handle leap years and odd/even number of days in a month correctly. The result of following code is a bit confusing but reasonable.

import { dateDiff } from "date-differencer";

const a = new Date("2020-02-27");
const b = new Date("2021-03-01");

console.log(dateDiff(a, b));
/*
{
    "years": 1,
    "months": 0,
    "days": 2
}

Explanation:
    1. 2020-02-27 + 1 year -> 2021-02-27
    2. 2021-02-27 + 2 days -> 2021-03-01 (2021-02 has 28 days)
*/

console.log(dateDiff(b, a));
/*
{
    "years": -1,
    "months": 0,
    "days": -3
}

Explanation:
    1. 2021-03-01 - 1 year -> 2020-03-01
    2. 2020-03-01 - 3 days -> 2020-02-27 (2020-02 has 29 days)
*/

Usage for Browsers

Source

Demo Page

License

MIT

0.3.2

7 months ago

0.3.1

1 year ago

0.3.0

1 year ago

0.2.9

1 year ago

0.2.8

1 year ago

0.2.7

1 year ago

0.2.6

1 year ago

0.2.5

1 year ago

0.2.4

1 year ago

0.2.3

1 year ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago