Open In App

Moment.js Customize Invalid Date

The Locale#invalidDate in Moment.js: The invalidate property should be a string, a replacement for the “Invalid Date” message you want to customize. Before proceeding, please install the moment.js library using the following command.

Installation:



npm install moment

Syntax:

const moment = require('moment')

moment.updateLocale("language_code", {
    invalidDate: "Custom Message"
});

After customizing the invalid date message using the above syntax, you can use those formats at the moment().format() utility method.



const moment = require('moment')
moment().format(dateFormat: String) 

Parameters: The moment().format() takes a string parameter representing the format in which you want to format your date.

Return value: It returns the date (in the string) in the format which was passed as the argument. If the date or dateFormat passed is incorrect, the custom invalid date message will show up in the console. 

Example 1: In this example, let’s change the Invalid Date message in French to a customized message.

Filename: main.js




const moment = require('moment');
 
moment.updateLocale("fr", {
    invalidDate: "Date invalide!!!"
});
 
let data = '2020X-05-30 00:00:00'
console.log(moment(data).format('DD/MM/YYYY'));

Steps to run the application:

node main.js

Output:

 

Example 2: In this example, let’s change the Invalid Date message in Italian to a customized message.

Filename: main.js




const moment = require('moment');
 
moment.updateLocale("it", {
    invalidDate: "data non valida!!!"
});
 
let data = '2020-05-3000:00:00'
console.log(moment(data).format('DD/MM/YYYY'));

Steps to run the application:

node main.js

Output:

 

Reference: https://momentjs.com/docs/#/customization/invalid-date/

Article Tags :