Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

diff-ymd-package

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

diff-ymd-package - npm Package Compare versions

Comparing version 1.1.3 to 2.0.0

docs/global.html

41

CHANGELOG.md

@@ -91,8 +91,43 @@ ## Changelog

### [Next Release] - Planning release time
### [v2.0.0] - [2024-01-24]
#### Added
- **Simplification:** Updated the `DatesYMD` class to accept dateString, epoch, and dateObject as well along with string as parameters.
- Added the method `diffInMonths` to calculate the difference in months between two dates.
- Added the method `diffInWeeks` to calculate the difference in weeks between two dates.
- Added the method `diffInDays` to calculate the difference in days between two dates.
- Added the method `diffInYears` to calculate the difference in years between two dates.
- Added the method `diffInHours` to calculate the difference in hours between two dates.
- Added the method `diffInMinutes` to calculate the difference in minutes between two dates.
- Added the method `diffInSeconds` to calculate the difference in seconds between two dates.
- Updated Unit tests: Included comprehensive Jest tests for the newly added methods.
- Updated the README.md documentation to include the new methods.
#### Changed
- Improved algorithm efficiency: Enhanced performance for existing methods to provide faster calculations.
- Modified internal structure: Refactored internal code for better readability and maintainability.
#### Fixed
- Fixed some issues related to the new changes.
- Configured files for publishing diff-ymd-package v2.0.0 on npm registry.
#### Documentation
- README.md updated: Added examples and use cases and api documentation for the new methods.
- Enhanced code comments: Provided thorough inline documentation for better codes understanding.
#### Testing
- Increased test coverage: Expanded Jest test suite to cover all scenarios, ensuring robust functionality.
- Continuous Integration: Integrated automated testing with GitHub Actions for ongoing code quality assurance.
### [Next Release] - Collecting issues and new features for next release
### Important changes links:
- [Unreleased](https://github.com/farhan7reza7/diff-ymd-package/compare/v1.1.3...HEAD)
- [v1.1.3](https://github.com/farhan7reza7/diff-ymd-package/releases/tag/v1.1.3)
- [Unreleased](https://github.com/farhan7reza7/diff-ymd-package/compare/v2.0.0...HEAD)
- [v2.0.0](https://github.com/farhan7reza7/diff-ymd-package/releases/tag/v2.0.0)
- [Next Release](https://github.com/farhan7reza7/diff-ymd-package/milestone/2)

11

package.json
{
"name": "diff-ymd-package",
"version": "1.1.3",
"description": "Utility class for calculating the difference between two dates in formatted ways like (aY bM cD)(aYears bMonths cDays) or customized formats like aY-bM-cD or aYears-bMonths-cDays etc.",
"version": "2.0.0",
"description": "A javascript library for calculating the difference between two dates in formatted ways like (aY bM cD)(aYears bMonths cDays) or customized desired formats like aY-bM-cD or aYears-bMonths-cDays or kDays or mWeeks or nMonths etc.",
"main": "src/diff-ymd.js",

@@ -13,4 +13,5 @@ "scripts": {

"diff-ymd",
"diff",
"diff-library",
"dates",
"time-intervals",
"formatted-difference",

@@ -20,3 +21,5 @@ "formatted-dates-difference",

"age",
"date",
"age-calculator",
"date-utility",
"desired-formats",
"customized-format",

@@ -23,0 +26,0 @@ "aY-bM-cD",

# diff-ymd-package
> `diff-ymd-package` a `javascript package` provides APIs to difference dates in formatted ways(like (aYears bMonths cDays) or (aY bM cD) etc., eg. age = 20Y 2M 23D or datesDifference = 2Years 11Months 20Days) or customized formats like aY-bM-cD or aYears-bMonths-cDays etc.
> `diff-ymd-package` a `javascript library` provides APIs to difference dates in formatted ways(like (aYears bMonths cDays) or (aY bM cD) etc., eg. age = 20Y 2M 23D or datesDifference = 2Years 11Months 20Days) or customized desired formats like aY-bM-cD or aYears-bMonths-cDays or kDays or mWeeks or nMonths etc.

@@ -20,3 +20,3 @@ [![NPM Version][npm-image]][npm-url]

### Install from `Github Packages` registry
### Install from `Github Packages registry`

@@ -31,2 +31,3 @@ ```bash

**Initialize**
```javascript

@@ -36,5 +37,6 @@ //const DatesYMD = require('@farhan7reza7/diff-ymd-package'); or

const DatesYMD = require('diff-ymd-package'); // can use any
```
```
**Create an instance**
```javascript

@@ -45,5 +47,17 @@ const date1 = '2022-01-01';

const Formatter = new DatesYMD(date1, date2);
```
**`OR` for version 2.x.x and above**
**Can use simplified function `diffDates` on module-object(DatesYMD here)**
```javascript
const date1 = '2022-01-01';
const date2 = '2023-12-31';
const Formatter = DatesYMD.diffDates(date1, date2); // can use any
```
**Use methods to format difference**
```javascript

@@ -59,4 +73,26 @@ // format output in aY bM cD format

// Calculate the difference in months
const monthsDifference = Formatter.diffInMonths(); // Output: 23
// Calculate the difference in weeks
const weeksDifference = Formatter.diffInWeeks(); // Output: 164
// Calculate the difference in days
const daysDifference = Formatter.diffInDays(); // Output: 1143
// Calculate the difference in years
const yearsDifference = Formatter.diffInYears(); // Output: 1
// Calculate the difference in hours
const hoursDifference = Formatter.diffInHours(); // Output: 27432
// Calculate the difference in minutes
const minutesDifference = Formatter.diffInMinutes(); // Output: 1645920
// Calculate the difference in seconds
const secondsDifference = Formatter.diffInSeconds(); // Output: 98755200
```
**Formatted Outputs**
```javascript

@@ -83,2 +119,22 @@ console.log(result); // Output: "1Y 11M 30D"

console.log(monthsDifference); // Output: 23
// Calculate the difference in months
console.log(weeksDifference); // Output: 164
// Calculate the difference in weeks
console.log(daysDifference); // Output: 1143
// Calculate the difference in days
console.log(yearsDifference); // Output: 1
// Calculate the difference in years
console.log(hoursDifference); // Output: 27432
// Calculate the difference in hours
console.log(minutesDifference); // Output: 1645920
// Calculate the difference in minutes
console.log(secondsDifference); // Output: 98755200
// Calculate the difference in seconds
```

@@ -90,3 +146,3 @@

Represents a utility class for calculating the formatted and customized difference between two dates in all cases.
Represents a utility class for calculating the formatted and desired customized difference between two dates in all cases.

@@ -99,8 +155,28 @@ #### Create an instance of `DatesYMD`:

- **`firstDate`**: The first date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or 'yyyy.mm.dd'.
- **`secondDate`**: The second date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or 'yyyy.mm.dd'.
#### `OR` for version 2.x.x and above
**Can use simplified function `diffDates` on module-object**
```javascript
//const DatesYMD = require('@farhan7reza7/diff-ymd-package'); or
const DatesYMD = require('diff-ymd-package');
const Formatter = DatesYMD.diffDates(firstDate, secondDate); // can use any
```
- **`firstDate`**: The first date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or 'yyyy.mm.dd' or dateString or dateObject
or Timestamp(epoch).
- **`secondDate`**: The second date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or 'yyyy.mm.dd' or dateString or dateObject
or Timestamp(epoch).
- **Special case:** empty string("" or '') is by default to current-date(today) for the parameters
- **`Returns:`**
An instance of DatesYMD class.
#### Methods:
**`diffArray`**
##### `diffArray()`
Calculates the difference between two dates and returns an array containing Y(years), M(months), D(days), and a formatted 'aY bM cD' difference string.

@@ -115,3 +191,4 @@

**`formattedYMD()`**
##### `formattedYMD()`
Returns the formatted difference between two dates in aY bM cD(aYears bMonths cDays) format.

@@ -125,3 +202,4 @@

**`customizeFormat(yearUnit, monthUnit, dayUnit, partSeparator)`**
##### `customizeFormat(yearUnit, monthUnit, dayUnit, partSeparator)`
Customizes the difference using specified units and separators

@@ -140,2 +218,72 @@

##### `diffInMonths()`
Calculates the difference in months between two dates.
```javascript
const monthsDifference = Formatter.diffInMonths();
```
- **Returns:** The difference in months.
##### `diffInWeeks()`
Calculates the difference in weeks between two dates.
```javascript
const weeksDifference = Formatter.diffInWeeks();
```
- **Returns:** The difference in weeks.
##### `diffInDays()`
Calculates the difference in days between two dates.
```javascript
const daysDifference = Formatter.diffInDays();
```
- **Returns:** The difference in days.
##### `diffInYears()`
Calculates the difference in years between two dates.
```javascript
const yearsDifference = Formatter.diffInYears();
```
- **Returns:** The difference in years.
##### `diffInHours()`
Calculates the difference in hours between two dates.
```javascript
const hoursDifference = Formatter.diffInHours();
```
- **Returns:** The difference in hours.
##### `diffInMinutes()`
Calculates the difference in minutes between two dates.
```javascript
const minutesDifference = Formatter.diffInMinutes();
```
- **Returns:** The difference in minutes.
##### `diffInSeconds()`
Calculates the difference in seconds between two dates.
```javascript
const secondsDifference = Formatter.diffInSeconds();
```
- **Returns:** The difference in seconds.
For more informations, [See `diff-ymd-package documentation`](https://farhan7reza7.github.io/diff-ymd-package/DatesYMD.html)

@@ -142,0 +290,0 @@

/**
* Represents a utility class for calculating the difference between two dates in (aYears bMonths cDays)(aY bM cD) format.
* Represents a javascript class for calculating the difference between two dates in formatted ways like (aY bM cD)(aYears bMonths cDays) or customized desired formats like aY-bM-cD or aYears-bMonths-cDays or nDays or mWeeks etc.
*

@@ -11,4 +11,6 @@ * @class

* @constructor
* @param {string} firstDate - The first date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or yyyy.mm.dd .
* @param {string} secondDate - The second date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd'or yyyy.mm.dd .
* @param {string} firstDate (type- String but Number for epoch, and Object for dateObject) - The first date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or yyyy.mm.dd or dateString or dateObject
or Timestamp(epoch).
* @param {string} secondDate (type- String but Number for epoch, and Object for dateObject) - The second date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or yyyy.mm.dd or dateString or dateObject
or Timestamp(epoch).
*/

@@ -18,2 +20,48 @@ constructor(firstDate, secondDate) {

this.secondDate = secondDate;
// Handle empty date inputs by defaulting to the current date
this.handleEmpty = function () {
var firstD, secondD;
if (this.firstDate === '' && this.secondDate === '') {
firstD = new Date();
secondD = new Date();
} else if (this.firstDate === '') {
firstD = new Date();
secondD = new Date(this.secondDate);
} else if (this.secondDate === '') {
firstD = new Date(this.firstDate);
secondD = new Date();
} else {
firstD = new Date(this.firstDate);
secondD = new Date(this.secondDate);
}
return [firstD, secondD];
};
// Swap dates if the first date is smaller than the second date
this.swapDates = function (firstD, secondD) {
if (firstD.getTime() < secondD.getTime()) {
var negativeHandle = firstD;
firstD = secondD;
secondD = negativeHandle;
}
return [firstD, secondD];
};
// initializing dates difference
this.initDiff = function () {
var dates, firstD, secondD;
// Handle empty date inputs by defaulting to the current date
dates = this.handleEmpty();
(firstD = dates[0]), (secondD = dates[1]);
// Swap dates if the first date is smaller than the second date
var swapped = this.swapDates(firstD, secondD);
if (swapped) {
(firstD = swapped[0]), (secondD = swapped[1]);
}
return [firstD, secondD];
};
}

@@ -28,35 +76,18 @@

diffArray() {
var datesDiff, year, month, day, firstD, secondD, monthAdjuster;
var datesDiff, year, month, day, monthAdjuster, firstD, secondD;
var dates, yearS, yearF, monthS, monthF, dateS, dateF;
// Handle empty date inputs by defaulting to the current date
if (this.firstDate === '' && this.secondDate === '') {
firstD = new Date();
secondD = new Date();
} else if (this.firstDate === '') {
firstD = new Date();
secondD = new Date(this.secondDate);
} else if (this.secondDate === '') {
firstD = new Date(this.firstDate);
secondD = new Date();
} else {
firstD = new Date(this.firstDate);
secondD = new Date(this.secondDate);
}
// initializing dates difference
dates = this.initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// Swap dates if the first date is smaller than the second date
if (firstD.getTime() < secondD.getTime()) {
var negativeHandle = firstD;
firstD = secondD;
secondD = negativeHandle;
}
// Extract year, month, and date components of the two dates
var yearS = secondD.getFullYear();
var yearF = firstD.getFullYear();
yearS = secondD.getFullYear();
yearF = firstD.getFullYear();
var monthS = secondD.getMonth() + 1;
var monthF = firstD.getMonth() + 1;
monthS = secondD.getMonth() + 1;
monthF = firstD.getMonth() + 1;
var dateS = secondD.getDate();
var dateF = firstD.getDate();
dateS = secondD.getDate();
dateF = firstD.getDate();

@@ -177,5 +208,498 @@ // Calculate the difference in years, months, and days

}
/**
* Calculates the difference in months between two dates.
*
* @method
* @returns {number} The difference in months.
*/
diffInMonths() {
var ymdArray, year, month;
// initializing dates difference
ymdArray = this.diffArray();
// Extract year, month, and date components of the difference
(year = ymdArray[0]), (month = ymdArray[1]);
// calculate months
const months = year * 12 + month;
return months;
}
/**
* Calculates the difference in weeks between two dates.
*
* @method
* @returns {number} The difference in weeks.
*/
diffInWeeks() {
let dates, weeks, firstD, secondD;
// initializing dates difference
dates = this.initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// calculate weeks
weeks = Math.floor(
(firstD.getTime() - secondD.getTime()) / (7 * 24 * 60 * 60 * 1000),
);
return weeks;
}
/**
* Calculates the difference in days between two dates.
*
* @method
* @returns {number} The difference in days.
*/
diffInDays() {
let dates, days, firstD, secondD;
// initializing dates difference
dates = this.initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// calculate days
days = Math.floor(
(firstD.getTime() - secondD.getTime()) / (24 * 60 * 60 * 1000),
);
return days;
}
/**
* Calculates the difference in years between two dates.
*
* @method
* @returns {number} The difference in years.
*/
diffInYears() {
let ymdArray, years;
// get dates difference array
ymdArray = this.diffArray();
// Extract year component of the difference
years = ymdArray[0];
return years;
}
/**
* Calculates the difference in hours between two dates.
*
* @method
* @returns {number} The difference in hours.
*/
diffInHours() {
let days, hours;
// get dates difference days
days = this.diffInDays();
// calculate hours
hours = days * 24;
return hours;
}
/**
* Calculates the difference in minutes between two dates.
*
* @method
* @returns {number} The difference in minutes.
*/
diffInMinutes() {
let minutes, hours;
// get dates difference hours
hours = this.diffInHours();
// calculate minutes
minutes = hours * 60;
return minutes;
}
/**
* Calculates the difference in seconds between two dates.
*
* @method
* @returns {number} The difference in seconds.
*/
diffInSeconds() {
let seconds, minutes;
// get dates difference minutes
minutes = this.diffInMinutes();
// calculate seconds
seconds = minutes * 60;
return seconds;
}
}
// Export the DatesYMD class for use in other modules
module.exports = DatesYMD;
/**
* Represents a utility for calculating the difference between two dates in formatted or desired customized ways.
*
* @typedef {Object} DatesYMD
* @property {Function} diffArray - Calculates the difference between two dates and returns an array containing years, months, days, and a formatted difference string.
* @property {Function} formattedYMD - Returns the formatted difference between two dates.
* @property {Function} customizeFormat - Customizes the difference using specified units and separators.
* @property {Function} diffInMonths - Calculates the difference in months between two dates.
* @property {Function} diffInWeeks - Calculates the difference in weeks between two dates.
* @property {Function} diffInDays - Calculates the difference in days between two dates.
* @property {Function} diffInYears - Calculates the difference in years between two dates.
* @property {Function} diffInHours - Calculates the difference in hours between two dates.
* @property {Function} diffInMinutes - Calculates the difference in minutes between two dates.
* @property {Function} diffInSeconds - Calculates the difference in seconds between two dates.
*/
/**
* Creates an instance of DatesYMD.
*
* @param {string} firstDate (type- String but Number for epoch, and Object for dateObject) - The first date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or yyyy.mm.dd or dateString or dateObject
or Timestamp(epoch).
* @param {string} secondDate (type- String but Number for epoch, and Object for dateObject) - The second date in the format 'yyyy-mm-dd' or 'yyyy/mm/dd' or yyyy.mm.dd or dateString or dateObject
or Timestamp(epoch).
*
* @returns {DatesYMD} An object containing methods for date difference calculations.
*/
function diffDates(firstDate, secondDate) {
/**
* Handles empty date inputs by defaulting to the current date.
*
* @function
* @returns {Array} An array containing the first and second date objects.
*/
function handleEmpty() {
var firstD, secondD;
if (firstDate === '' && secondDate === '') {
firstD = new Date();
secondD = new Date();
} else if (firstDate === '') {
firstD = new Date();
secondD = new Date(secondDate);
} else if (secondDate === '') {
firstD = new Date(firstDate);
secondD = new Date();
} else {
firstD = new Date(firstDate);
secondD = new Date(secondDate);
}
return [firstD, secondD];
}
/**
* Swaps dates if the first date is smaller than the second date.
*
* @function
* @param {Date} firstD - The first date object.
* @param {Date} secondD - The second date object.
* @returns {Array} An array containing the first and second date objects.
*/
function swapDates(firstD, secondD) {
if (firstD.getTime() < secondD.getTime()) {
var negativeHandle = firstD;
firstD = secondD;
secondD = negativeHandle;
}
return [firstD, secondD];
}
/**
* Initializes dates difference.
*
* @function
* @returns {Array} An array containing the first and second date objects.
*/
function initDiff() {
var dates, firstD, secondD;
// Handle empty date inputs by defaulting to the current date
dates = handleEmpty();
[firstD, secondD] = dates;
// Swap dates if the first date is smaller than the second date
var swapped = swapDates(firstD, secondD);
if (swapped) {
[firstD, secondD] = swapped;
}
return [firstD, secondD];
}
return {
/**
* Calculates the difference between two dates and returns an array containing years, months, days, and a formatted difference string.
*
* @returns {Array} An array containing the calculated years, months, days, and the formatted difference.
*/
diffArray: function () {
var datesDiff, year, month, day, monthAdjuster, firstD, secondD;
var dates, yearS, yearF, monthS, monthF, dateS, dateF;
// initializing dates difference
dates = initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// Extract year, month, and date components of the two dates
yearS = secondD.getFullYear();
yearF = firstD.getFullYear();
monthS = secondD.getMonth() + 1;
monthF = firstD.getMonth() + 1;
dateS = secondD.getDate();
dateF = firstD.getDate();
// Calculate the difference in years, months, and days
if (monthF >= monthS && dateF >= dateS) {
year = yearF - yearS;
month = monthF - monthS;
day = dateF - dateS;
} else if (monthF < monthS && dateF >= dateS) {
// Handle the case where the months are different, and the first date's day is greater than or equal to the second date's day
day = dateF - dateS;
month = monthF + 12 - monthS;
year = yearF - 1 - yearS;
} else if (monthF > monthS && dateF < dateS) {
// Handle the case where the months are different, and the first date's day is less than the second date's day
month = monthF - monthS - 1;
year = yearF - yearS;
// Save the first last month of monthF for correct aY bM cD following mathematical finding algorithm for calculating aY bM cD correctly like if 2020-05-22 to 2021-03-20, then firstly decide monthAdjuster which is (greaterDate month - 1), that is 03 - 1 = 02, then find month from 20-05 to 21-02(02 is monthAdjuster) i.e 9M, and then decide days from 2021-02-22 to 2021-03-20
monthAdjuster = monthF - 1; // for getting intuitively correct - aY bM cD in all cases
// Further adjustments based on specific conditions
if (monthAdjuster === 2) {
// Handle February
if (yearF % 4 === 0) {
// Leap year logic
day = dateF > 29 ? dateF : 29 - dateS + dateF;
} else {
// Non-leap year logic
day = dateF > 28 ? dateF : 28 - dateS + dateF;
}
} else if (
// handle 30 days months
monthAdjuster === 4 ||
monthAdjuster === 6 ||
monthAdjuster === 8 ||
monthAdjuster === 11
) {
// Handle months with 30 days
day = dateF > 30 ? dateF : 30 - dateS + dateF;
} else {
// Handle months with 31 days
day = 31 - dateS + dateF;
}
} else if (monthF <= monthS && dateF < dateS) {
// Handle the case where the months are either different or equal, and the first date's day is less than the second date's day
month = monthF + 11 - monthS;
year = yearF - 1 - yearS;
monthAdjuster = monthF - 1; // for getting intuitively correct - aY bM cD
// Further adjustments based on specific conditions
if (monthAdjuster === 2) {
// Handle February
if (yearF % 4 === 0) {
// Leap year logic
day = dateF > 29 ? dateF : 29 - dateS + dateF;
} else {
// Non-leap year logic
day = dateF > 28 ? dateF : 28 - dateS + dateF;
}
} else if (
// handle 30 days months
monthAdjuster === 4 ||
monthAdjuster === 6 ||
monthAdjuster === 8 ||
monthAdjuster === 11
) {
// Handle months with 30 days
day = dateF > 30 ? dateF : 30 - dateS + dateF;
} else {
// Handle months with 31 days
day = 31 - dateS + dateF;
}
}
// Format the difference and return the result
const diffFormat = year + 'Y ' + month + 'M ' + day + 'D';
datesDiff = [year, month, day, diffFormat];
return datesDiff;
},
/**
* Returns the formatted difference between two dates.
*
* @returns {string} The formatted difference in the format 'aY bM cD'.
*/
formattedYMD: function () {
return this.diffArray()[3];
},
/**
* Customizes the difference using specified units and separators like (a + yearUnit + partSeparator + b + monthUnit + partSeparator + c + dayUnit), eg. aYs-bMs-cDs etc.
*
* @param {string} yearUnit - The unit for years.
* @param {string} monthUnit - The unit for months.
* @param {string} dayUnit - The unit for days.
* @param {string} partSeparator - The separator between year, month, and day parts.
* @returns {string} The customized formatted difference.
*/
customizeFormat: function (yearUnit, monthUnit, dayUnit, partSeparator) {
let Y, M, D;
Y = this.diffArray()[0];
M = this.diffArray()[1];
D = this.diffArray()[2];
const customized =
Y +
yearUnit +
partSeparator +
M +
monthUnit +
partSeparator +
D +
dayUnit;
return customized;
},
/**
* Calculates the difference in months between two dates.
*
* @returns {number} The difference in months.
*/
diffInMonths: function () {
var ymdArray, year, month;
// initializing dates difference
ymdArray = this.diffArray();
// Extract year, month, and date components of the difference
(year = ymdArray[0]), (month = ymdArray[1]);
// calculate months
const months = year * 12 + month;
return months;
},
/**
* Calculates the difference in weeks between two dates.
*
* @returns {number} The difference in weeks.
*/
diffInWeeks: function () {
let dates, weeks, firstD, secondD;
// initializing dates difference
dates = initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// calculate weeks
weeks = Math.floor(
(firstD.getTime() - secondD.getTime()) / (7 * 24 * 60 * 60 * 1000),
);
return weeks;
},
/**
* Calculates the difference in days between two dates.
*
* @returns {number} The difference in days.
*/
diffInDays: function () {
let dates, days, firstD, secondD;
// initializing dates difference
dates = initDiff();
(firstD = dates[0]), (secondD = dates[1]);
// calculate days
days = Math.floor(
(firstD.getTime() - secondD.getTime()) / (24 * 60 * 60 * 1000),
);
return days;
},
/**
* Calculates the difference in years between two dates.
*
* @returns {number} The difference in years.
*/
diffInYears: function () {
let ymdArray, years;
// get dates difference array
ymdArray = this.diffArray();
// Extract year component of the difference
years = ymdArray[0];
return years;
},
/**
* Calculates the difference in hours between two dates.
*
* @returns {number} The difference in hours.
*/
diffInHours: function () {
let days, hours;
// get dates difference days
days = this.diffInDays();
// calculate hours
hours = days * 24;
return hours;
},
/**
* Calculates the difference in minutes between two dates.
*
* @returns {number} The difference in minutes.
*/
diffInMinutes: function () {
let minutes, hours;
// get dates difference hours
hours = this.diffInHours();
// calculate minutes
minutes = hours * 60;
return minutes;
},
/**
* Calculates the difference in seconds between two dates.
*
* @returns {number} The difference in seconds.
*/
diffInSeconds: function () {
let seconds, minutes;
// get dates difference minutes
minutes = this.diffInMinutes();
// calculate seconds
seconds = minutes * 60;
return seconds;
},
};
}
// Export the DatesYMD class and closure function diffDates for usages in other modules
module.exports = DatesYMD; // default export for class
module.exports.diffDates = diffDates; // named export for closure

@@ -1,10 +0,15 @@

// dates-ymd.test.js
// Import the exported codes(class: DatesYMD, and closure: diffDates) from source codes file
const diffCalculator = require('../src/diff-ymd');
// Import the DatesYMD class from your source code
const DatesYMD = require('../src/diff-ymd');
// Given dates for testing
const date1 = '2022-01-01';
const date2 = '2023-02-15';
// Describe block for the DatesYMD class
describe('DatesYMD', () => {
// Create an instance of DatesYMD for testing
const differ = new diffCalculator(date1, date2);
// Describe block for the diffCalculator class
describe('diffCalculator', () => {
// Test case to check if the difference between two dates is calculated correctly
test('should calculate the difference between two dates', () => {
test('calculates the difference between two dates', () => {
// Input dates for the test case

@@ -14,4 +19,4 @@ const date1 = '2022-01-01';

// Create an instance of the DatesYMD class with the input dates
const datesYMD = new DatesYMD(date1, date2);
// Create an instance of the diffCalculator class with the input dates
const datesYMD = new diffCalculator(date1, date2);
// Calculate the difference and get the result array

@@ -25,5 +30,5 @@ const diffArray = datesYMD.diffArray();

// Test case to check if the class handles empty date inputs
test('should handle empty date inputs', () => {
// Create an instance of the DatesYMD class with empty date inputs
const datesYMD = new DatesYMD('', '');
test('handles empty date inputs', () => {
// Create an instance of the diffCalculator class with empty date inputs
const datesYMD = new diffCalculator('', '');
// Calculate the difference and get the result array

@@ -43,3 +48,3 @@ const diffArray = datesYMD.diffArray();

// Test case to check if the formatted difference is generated correctly
test('should format the difference between two dates like aY bM cD', () => {
test('formats the difference between two dates like aY bM cD', () => {
// Input dates for the test case

@@ -49,4 +54,4 @@ const date1 = '2021-03-20';

// Create an instance of the DatesYMD class with the input dates
const datesYMD = new DatesYMD(date1, date2);
// Create an instance of the diffCalculator class with the input dates
const datesYMD = new diffCalculator(date1, date2);
// Get the formatted difference

@@ -60,3 +65,3 @@ const formattedDifference = datesYMD.formattedYMD();

// Test case to check if the customized difference is generated correctly
test('should customized the difference between two dates like (a + yearUnit + partSeparator + b + monthUnit + partSeparator + c + dayUnit), eg. aYs-bMs-cDs etc.', () => {
test('customizes the difference between two dates like (a + yearUnit + partSeparator + b + monthUnit + partSeparator + c + dayUnit), e.g., aYs-bMs-cDs etc.', () => {
// Input dates for the test case

@@ -66,4 +71,4 @@ const date1 = '2021-03-20';

// Create an instance of the DatesYMD class with the input dates
const datesYMD = new DatesYMD(date1, date2);
// Create an instance of the diffCalculator class with the input dates
const datesYMD = new diffCalculator(date1, date2);
// Get the customized difference

@@ -80,2 +85,181 @@ const customizedDifference = datesYMD.customizeFormat(

});
// Test for diffInMonths()
test('calculates the difference in months between two dates', () => {
const monthsDifference = differ.diffInMonths();
// Assuming date1 to date2 has a difference of 13 months
expect(monthsDifference).toBe(13);
});
// Test for diffInWeeks()
test('calculates the difference in weeks between two dates', () => {
const weeksDifference = differ.diffInWeeks();
// Assuming date1 to date2 has a difference of 56 weeks
expect(weeksDifference).toBe(58);
});
// Test for diffInDays()
test('calculates the difference in days between two dates', () => {
const daysDifference = differ.diffInDays();
// Assuming date1 to date2 has a difference of 410 days
expect(daysDifference).toBe(410);
});
// Test for diffInYears()
test('calculates the difference in years between two dates', () => {
const yearsDifference = differ.diffInYears();
// Assuming date1 to date2 has a difference of 1 year
expect(yearsDifference).toBe(1);
});
// Test for diffInHours()
test('calculates the difference in hours between two dates', () => {
const hoursDifference = differ.diffInHours();
// Assuming date1 to date2 has a difference of 9840 hours
expect(hoursDifference).toBe(9840);
});
// Test for diffInMinutes()
test('calculates the difference in minutes between two dates', () => {
const minutesDifference = differ.diffInMinutes();
// Assuming date1 to date2 has a difference of 590400 minutes
expect(minutesDifference).toBe(590400);
});
// Test for diffInSeconds()
test('calculates the difference in seconds between two dates', () => {
const secondsDifference = differ.diffInSeconds();
// Assuming date1 to date2 has a difference of 35424000 seconds
expect(secondsDifference).toBe(35424000);
});
});
// tests for closure function named diffDates
describe('diffDates', () => {
let dateCalculator;
beforeEach(() => {
// Setting up a new instance for each test
dateCalculator = diffCalculator.diffDates('2022-01-01', '2022-01-15');
});
afterEach(() => {
// Cleaning up after each test
dateCalculator = null;
});
// Test suite for diffArray function
describe('diffArray', () => {
test('calculates the difference array correctly', () => {
// Act
const result = dateCalculator.diffArray();
// Assert
expect(result).toEqual([0, 0, 14, '0Y 0M 14D']);
});
});
// Test suite for formattedYMD function
describe('formattedYMD', () => {
test('returns the formatted difference string', () => {
// Act
const result = dateCalculator.formattedYMD();
// Assert
expect(result).toBe('0Y 0M 14D');
});
});
// Test suite for customizeFormat function
describe('customizeFormat', () => {
test('customizes the difference using specified units and separators', () => {
// Act
const result = dateCalculator.customizeFormat(
' years',
' months',
' days',
'-',
);
// Assert
expect(result).toBe('0 years-0 months-14 days');
});
});
// Test suite for diffInMonths function
describe('diffInMonths', () => {
test('calculates the difference in months correctly', () => {
// Act
const result = dateCalculator.diffInMonths();
// Assert
expect(result).toBe(0);
});
});
// Test suite for diffInWeeks function
describe('diffInWeeks', () => {
test('calculates the difference in weeks correctly', () => {
// Act
const result = dateCalculator.diffInWeeks();
// Assert
expect(result).toBe(2);
});
});
// Test suite for diffInDays function
describe('diffInDays', () => {
test('calculates the difference in days correctly', () => {
// Act
const result = dateCalculator.diffInDays();
// Assert
expect(result).toBe(14);
});
});
// Test suite for diffInYears function
describe('diffInYears', () => {
test('calculates the difference in years correctly', () => {
// Act
const result = dateCalculator.diffInYears();
// Assert
expect(result).toBe(0);
});
});
// Test suite for diffInHours function
describe('diffInHours', () => {
test('calculates the difference in hours correctly', () => {
// Act
const result = dateCalculator.diffInHours();
// Assert
expect(result).toBe(336);
});
});
// Test suite for diffInMinutes function
describe('diffInMinutes', () => {
test('calculates the difference in minutes correctly', () => {
// Act
const result = dateCalculator.diffInMinutes();
// Assert
expect(result).toBe(20160);
});
});
// Test suite for diffInSeconds function
describe('diffInSeconds', () => {
test('calculates the difference in seconds correctly', () => {
// Act
const result = dateCalculator.diffInSeconds();
// Assert
expect(result).toBe(1209600);
});
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc