Ben
Ben

Reputation: 16534

custom long date format in moment js

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 format that will print the long date for the locale (including the year), but if I wanted to add my own that excluded the year like this:

moment().format("LTY") that just printed the month and day in a given locale.

How can I do this?

Upvotes: 3

Views: 14581

Answers (1)

RobG
RobG

Reputation: 147483

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: "dddd, 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 : 'dddd, 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: "dddd, 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.

Upvotes: 9

Related Questions