Get month name from Date

前端 未结 30 2873
情歌与酒
情歌与酒 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:54

    For me this is best solution is,

    for TypeScript as well

    const env = process.env.REACT_APP_LOCALE || 'en';
    
    const namedMonthsArray = (index?: number): string[] | string => {
      const months = [];
    
      for (let month = 0; month <= 11; month++) {
        months.push(
          new Date(new Date('1970-01-01').setMonth(month))
            .toLocaleString(env, {
              month: 'long',
            })
            .toString(),
        );
      }
      if (index) {
        return months[index];
      }
      return months;
    };
    

    Output is

    ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    

提交回复
热议问题