Get month name from Date

前端 未结 30 3592
情歌与酒
情歌与酒 2020-11-22 00:16

How can I generate the name of the month (e.g: Oct/October) from this date object in JavaScript?

var objDate = new Date(\"10/11/2009\");
30条回答
  •  感动是毒
    2020-11-22 00:59

    You can handle with or without translating to the local language

    1. Generates value as "11 Oct 2009"

    const objDate = new Date("10/11/2009");
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    if (objDate !== 'Invalid Date' && !isNaN(objDate)) {
      console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())
    }

    1. The ECMAScript Internationalization API to translate month to local language (eg: 11 octobre)

    const convertDate = new Date('10/11/2009')
    const lang = 'fr' // de, es, ch 
    if (convertDate !== 'Invalid Date' && !isNaN(convertDate)) {
      console.log(convertDate.getDate() + ' ' + convertDate.toLocaleString(lang, {
        month: 'long'
      }))
    }

提交回复
热议问题