MomentJS - Utilities
Modern Date/Time: Moment.js Utilities
Section titled “Modern Date/Time: Moment.js Utilities”Moment.js includes a few utility functions that assist with input normalization and creating invalid moment objects explicitly.
Normalize Units
Section titled “Normalize Units”moment.normalizeUnits(String): This utility converts aliases and plural forms of time units into the canonical unit name used internally by Moment.js.
It’s primarily used internally by Moment.js itself when parsing inputs for methods like add, subtract, startOf, etc., but you can call it directly.
console.log(moment.normalizeUnits('Years')); // Output: 'year'console.log(moment.normalizeUnits('y')); // Output: 'year'console.log(moment.normalizeUnits('Months')); // Output: 'month'console.log(moment.normalizeUnits('M')); // Output: 'month'console.log(moment.normalizeUnits('Days')); // Output: 'day'console.log(moment.normalizeUnits('d')); // Output: 'day'console.log(moment.normalizeUnits('Minutes')); // Output: 'minute'console.log(moment.normalizeUnits('m')); // Output: 'minute'This can be helpful if you are building functions that accept flexible unit strings and need to standardize them before passing them to Moment.js methods.
Create Invalid Moment
Section titled “Create Invalid Moment”moment.invalid(Object): Creates an explicitly invalid Moment object. This is useful in scenarios where you need to return a Moment object from a function but indicate that the operation failed or the resulting date is not valid.
The optional object argument allows setting parsing flags for the invalid moment, primarily parsingFlags.userInvalidated = true.
function calculateFutureDate(input, daysToAdd) { const startMoment = moment(input); if (!startMoment.isValid() || typeof daysToAdd !== 'number' || daysToAdd <= 0) { // Return an invalid moment if input is bad return moment.invalid(); } return startMoment.add(daysToAdd, 'days');}
const validResult = calculateFutureDate('2023-10-26', 5);console.log('Valid Result Is Valid:', validResult.isValid()); // trueconsole.log('Valid Result:', validResult.format('YYYY-MM-DD')); // 2023-10-31
const invalidResult = calculateFutureDate('Some Bad Date', 5);console.log('Invalid Result Is Valid:', invalidResult.isValid()); // false
const invalidResultFlags = invalidResult.parsingFlags();console.log('Invalid Result User Invalidated:', invalidResultFlags.userInvalidated); // trueUsing moment.invalid() provides a consistent way to signal failure within functions that are expected to return Moment objects.
These utilities are less frequently used than core manipulation or formatting methods but serve specific purposes in advanced scenarios or internal library logic.
See the docs: https://momentjs.com/docs/#/utilities/