Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do can I add a new format option to Moment.js locales?

I want to be able to format a date as the day and the shortened month. (ex: 20 Sep for en-gb, Sep 20 for en). However, the closest localized format that Moment.js has us the format 'll' which is Sep 20, 2017 for en. I want to be able to create a new format that excludes the year from 'll'. How can I best achieve this?

The end result I want (assuming today is Sept 20):

moment.locale('en');
moment().format('my-new-format')  ---> Sep 20
moment.locale('en-gb');
moment().format('my-new-format')  ---> 20 Sep
moment().format('ll')             ---> 20 Sep, 2017
like image 446
breakfast Avatar asked Sep 20 '17 01:09

breakfast


People also ask

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

Is MomentJS being deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How do I change a locale moment?

You set locale with moment. locale('de') , and you create a new object representing the date of now by moment() (note the parenthesis) and then format('LLL') it. The parenthesis is important.


1 Answers

That seems to work with me... :

moment.updateLocale("en", { longDateFormat : { "[my-new-format]" : "MMM D" } });
moment.updateLocale("en-gb", { longDateFormat : { "[my-new-format]" : "DD MMM" } });

And then

moment.locale('en');
moment().format('[my-new-format]');

So you don't overwrite existing formats.

like image 57
cedrik Avatar answered Oct 10 '22 11:10

cedrik