format date using moment with custom format

2019-07-25 10:17发布

问题:

var format = 'EEEE, D 'de' MMMM 'de' Y'
moment(date).format(format);

I have a custom format and use it with moment and got this

exp: segunda-feira, 2 de janeiro de 2017
act: Segunda-feira, 2 11 Janeiro 11 2017

Note the placeholder de in the pattern actually got parsed .. Is there a way for me to get the date in the expected format segunda-feira, 2 de janeiro de 2017 using moment?

回答1:

You have to use [] square brackets to escape characters in format string, see format docs:

To escape characters in format strings, you can wrap the characters in square brackets.

Moreover note that there is no EEEE token in moment, but the single E represents Day of Week (ISO), so in your case you will have 2222. Use dddd to get the desidered output.

Here a working example:

var date = '2017-01-02';
var format = 'dddd, D [de] MMMM [de] YYYY';
console.log(moment(date).format(format));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/locale/pt.js"></script>



回答2:

To escape characters in format strings, you can wrap the characters in square brackets.

var momObj = moment();
var format = 'EEEE, D [de] MMMM [de] Y';
var fString = momObj.format(format);
console.log(fString);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>