I am using Moment.js in my project and formatting dates as follows:
var locale = window.navigator.userLanguage || window.navigator.language; moment.locale(locale); someDate.format("L");
It works well but sometimes I need show a date without a year. I can't use something like someDate.format("MM/DD")
because in some languages it should be someDate.format("DD/MM")
. I need something like L,LL,LLL
but without the year.
What can I do?
LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT'
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.
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.
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.
Okay. This is a little awful, but you knew it was going to be.
First, you can access the actual format string for (for instance) 'L'
:
var formatL = moment.localeData().longDateFormat('L');
Next, you can perform some surgery on it with judicious regex replacement:
var formatYearlessL = formatL.replace(/Y/g,'').replace(/^\W|\W$|\W\W/,'');
(Which is to say: Remove YYYY, plus the orphaned separator left by its removal)
Then you can use your new format string in a moment format call:
someDate.format(formatYearlessL);
This necessarily makes some assumptions:
On a quick review of locale/*.js
, these assumptions hold true for every locale file I examined, but there may be some locales that violate them. (ETA: a comment below points out that a German short date format violates the second assumption)
As an additional important caveat, this is likely to be fragile. It is entirely possible that a future version of moment.js will change the location of the data currently in longDateFormat
...
As far as I understand, you can change the date format(without year) for specific languages using MomentJS properties https://momentjs.com/docs/#/customization/long-date-formats/
Example:
moment.updateLocale('en', { longDateFormat: { LLL: "MMMM Do, LT", // Oct 6th, 4:27 PM } }); moment.updateLocale('ru', { longDateFormat: { LLL : 'D MMMM, HH:mm', // 6 окт., 16:27 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With