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

前端 未结 15 1955
北海茫月
北海茫月 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:45

    Here:

    JSFiddle

    const nth = function(d) {
      if (d > 3 && d < 21) return 'th';
      switch (d % 10) {
        case 1:  return "st";
        case 2:  return "nd";
        case 3:  return "rd";
        default: return "th";
      }
    }
    
    const fortnightAway = new Date(+new Date + 12096e5);
    const date = fortnightAway.getDate();
    const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][fortnightAway.getMonth()];
    
    document.getElementById("date").innerHTML = `In two weeks it will be the ${date}${nth(date)} ${month} ${fortnightAway.getFullYear()}`;
    
    // test
    const dates = [...Array(32).keys()].slice(1).map(i => `${i}${nth(i)}`)
    console.log(dates.join(", "))
    sup {
      font-size: x-small
    }

提交回复
热议问题