简体   繁体   中英

format date using moment with custom format

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?

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM