UNPKG

sectom

Version:

Sectom is a useful npm package that has multiple easy to use functions.

104 lines (88 loc) 2.92 kB
const { DateTime } = require("luxon"); const { stringToBoolean } = require("./stringToBoolean"); const format = require("./formatter"); const DATE_ISO_STRING = new Date().toISOString(); /** * @description Shows the difference between the current date and another date passed from an ISO format * * * @param {DATE_ISO_STRING} date * @param {boolean} includeMinutes * @param {boolean} boldForEach * @returns {string} - A string showing the difference between 2 dates * @example * * // ------------------------------------------------- * console.log(DateDiffer("2011-10-05T14:48:00.000Z")) * * "9 years 9 months 8 days 2 hours and 56 minutes ago" * * * // ------------------------------------------------- * console.log(DateDiffer("2011-10-05T14:48:00.000Z", false)) * * "9 years 9 months 8 days and 2 hours ago" * * * // ------------------------------------------------- * console.log(DateDiffer("2011-10-05T14:48:00.000Z"), true, true) * * "**9** years **9** months **8** days **2** hours and **56** minutes ago" * * console.log(DateDiffer("2011-10-05T14:48:00.000Z", false, true)) * * "**9** years **9** months **8** days and **2** hours ago" */ function DateDiffer(date, includeMinutes = true, boldForEach = false) { if (typeof includeMinutes != "boolean") includeMinutes = stringToBoolean(includeMinutes); if (typeof boldForEach != "boolean") boldForEach = stringToBoolean(boldForEach); const event = new Date().toISOString(); if (typeof date !== "string") { if (typeof date == "function") { date = date().toISOString(); } else { date = date.toISOString(); } } const event2 = date; const date1 = DateTime.fromISO(event); const date2 = DateTime.fromISO(event2); let arr = ["years", "months", `days`, `hours`]; if (includeMinutes == true) arr.push("minutes"); let diff = date1.diff(date2, arr); diff = diff.toObject(); let sentence2 = ``; const keys = Object.keys(diff); let i = 0; keys.forEach((key, indexNumber, main) => { const name = key.toString(); let value = diff[key]; if (!Number.isInteger(value)) { value = parseInt(value.toString().split(".")[0]); } if (indexNumber == main.length - 1 && i >= 1) { sentence2 += "and "; } if (value == 0) { } else { i++; if (name.endsWith("s") && value != 1) { sentence2 += `${ boldForEach == true ? `${format.defaults.bold(`${value}`)} ${name}` : `${value} ${name}` } `; } else { sentence2 += boldForEach == true ? `${format.defaults.bold(`${value}`)} ${name.slice(0, -1)}` : `${value} ${name.slice(0, -1)}`; } } }); sentence2 += "ago"; return sentence2; } exports.DateDiffer = DateDiffer;