JavaScript 新日期序数(st、nd、rd、th)

JavaScript 新日期序数(st、nd、rd、th)

问题描述:

如果可能的话,没有 JavaScript 库或大量笨重的代码,我正在寻找一种最简单的方法来格式化两周后的日期,格式如下:

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:

2013 年 3 月 13 日

我使用的代码是:

var newdate = new Date(+new Date + 12096e5);
document.body.innerHTML = newdate;

返回两周后的日期和时间,但像这样:2013 年 3 月 27 日星期三 21:50:29 GMT+0000(GMT 标准时间)

which returns the date and time two weeks from now, but like this: Wed Mar 27 2013 21:50:29 GMT+0000 (GMT Standard Time)

这是jsFiddle中的代码.

任何帮助将不胜感激!

这里:

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}<sup>${nth(date)}</sup> ${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
}

<span id="date"></span>