JavaScript new Date Ordinal (st, nd, rd, th)

前端 未结 15 1956
北海茫月
北海茫月 2020-11-27 03:12

If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:

<
15条回答
  •  醉酒成梦
    2020-11-27 03:58

    function getSuffixForDate(day) {
      const lastNumberOfTheDay = day[day.length];
    
      const suffixes = {
        1: () => 'st',
        21: () => 'st',
        31: () => 'st',
        2: () => 'nd',
        22: () => 'nd',
        3: () => 'rd',
        23: () => 'rd',
      };
    
      return suffixes[lastNumberOfTheDay] !== undefined ? `${day}${suffixes[lastNumberOfTheDay]()}` : `${day}th`;
    }
    
    const date = new Date();
    const formattedDate = `${getSuffixForDate(date.getDate())} ${monthNames[date.getMonth()]} ${date.getFullYear()}`;
    

    A human readable version...

提交回复
热议问题