Is there a way to add a custom format code to moment for long dates based on locale?
for example:
moment().format(\"L\")
is an existing for
Read the section on long date formats. You'd replace the default long date format object using:
moment.updateLocale('en', {
longDateFormat : {
LT: "h:mm A",
LTS: "h:mm:ss A",
L: "MM/DD", // Remove year
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "ffffdd, MMMM Do YYYY LT"
}
});
Then use:
var x = moment().format('L');
Moment parses the string passed to format looking for tokens. If you want to add a custom token like "LTY" you'll also need to add it to the list of local formatting tokens:
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
would change to (LTY added):
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTY|LTS|LT|LL?L?L?|l{1,4})/g;
and update the default long date formats with the new token:
var defaultLongDateFormat = {
LTY : 'MM/DD HH:mm', // format for new token
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'ffffdd, MMMM D, YYYY h:mm A'
};
then, if you wanted some other format:
moment.updateLocale('en', {
longDateFormat : {
LTY: 'MM/DD HH:mm', // new format for token here
LT: "h:mm A",
LTS: "h:mm:ss A",
L: "MM/DD/YYYY",
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "ffffdd, MMMM Do YYYY LT"
}
});
and finally:
var x = moment().format('LTY');
but you'd have to check what that is going to do to other code. Also, you'd have to apply the same changes every time you update the moment.js source, couldn't use a CDN and your code would not be portable to other sites using the standard moment.js library.
So stick to the updateLocale way of doing things. Or just do:
var LTY = 'MM/DD HH:mm';
var d = new moment().format(LTY);
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.js"></script>
and you're done.
Note that the use of "locale" here is a misnomer. Formatting preferences have nothing to do with where the user is located (i.e. their locale), and "en" is a language that is spoken in a huge number of locales which have very different preferences for how to format a date.