Last active
January 26, 2024 19:34
-
-
Save viceo/06733b1704058ed9ccd3358fc443584d to your computer and use it in GitHub Desktop.
Collection of helper functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Formatter { | |
| /** | |
| * | |
| * @param {string} x | |
| * Input string | |
| * - 1234-5678-4321-8765 | |
| * - $1,111.11 | |
| * @param {boolean} isMoney | |
| * Boolean switch, default FALSE | |
| * - If true '.' will be accepted and displayed like 1111.11 | |
| * - If false '.' won't be accepted and displayed like 111111 | |
| * @returns {string} Formatted string | |
| */ | |
| static numbersOnly(x, isMoney = false) { | |
| return isMoney | |
| ? x?.replace(/[^0-9\.\-]+/g, '') || null | |
| : x?.replace(/[^0-9]+/g, '') || null | |
| } | |
| /** | |
| * | |
| * @param {string} x | |
| * String number with leading zeros | |
| * @returns {string} Number without leading zeros | |
| */ | |
| static removeLeadingZeros(x) { | |
| return x?.replace(/^0+/, '') || '' | |
| } | |
| /** | |
| * | |
| * @param {Date} x | |
| * Date object to be formatted | |
| * @returns {string} | |
| * Date in unix format, compatible with MySQL | |
| */ | |
| static toUnixDate(x) { | |
| return x?.toISOString().slice(0, 19).replace('T', ' ') || null | |
| } | |
| /** | |
| * @method | |
| * Converts date object or string in valid UTC or ISO format to UNIX Date format | |
| * from the current timezone. You can set the Timezone as a ENV variable like | |
| * - process.env.TZ = 'America/Mexico_City' | |
| * @param {string | Date} x | |
| * - Date object | |
| * - Date in ISO string format | |
| * - Date in UTC string format | |
| * @returns {string} | |
| * Date in unix format, compatible with MySQL | |
| * @example | |
| * - getActualDate() | |
| * - getActualDate('2021-12-15T01:50:33.382Z') | |
| * - getActualDate(new Date().toISOString()) | |
| * - getActualDate(new Date().toUTCString()) | |
| */ | |
| static getActualDate(x = null) { | |
| let baseDate = new Date() | |
| if (x !== null) { | |
| if (typeof x === 'string' && !isNaN(Date.parse(x))) baseDate = new Date(x); | |
| if (typeof x === 'object' && x instanceof Date) baseDate = x; | |
| } | |
| const isoDateTime = new Date(baseDate.getTime() - baseDate.getTimezoneOffset() * 60000) | |
| return Formatter.toUnixDate(isoDateTime) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment