用序号后缀

时间:2019-06-04 06:24:06

标签: javascript

我想将日期格式设置为以下格式,例如:Thursday, May 2nd 2019

我创建了以下函数:

function convertDateToString(date) {
  let monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  let dayNames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

  let dayIndex = date.getDate();
  let monthIndex = date.getMonth();
  let year = date.getFullYear();

  return dayNames[dayIndex] + ', ' + monthNames[monthIndex] + ' ' + dayIndex + ' ' + year;
}

let date = new Date()

console.log(convertDateToString(date));

// wanted format: Thursday, May 2nd 2019

但是,我不确定如何在日期后添加序数后缀。我目前只获得完整号码,而没有1st2nd等。

任何建议如何添加此内容?

感谢您的答复!

4 个答案:

答案 0 :(得分:2)

您可以创建一个函数,该函数需要一个月的某天,例如2,并返回适当的后缀,例如nd(对于{{1,则为st }}(或21或31),在1(或23)的情况下为rd,在所有其他情况下的3):

th

答案 1 :(得分:2)

// Takes a number and return with ordinal suffix
const ordinal = (n) => {
  const s = ['th', 'st', 'nd', 'rd'];
  const m = n % 100;
  return n + (s[(m - 20) % 10] || s[m] || s[0]);
};

// See for yourself
for (let i = 1; i < 50; i++) {
    console.log(ordinal(i));
}

答案 2 :(得分:1)

您可以创建后缀数组。

function convertDateToString(date) {
  let monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];
  let suffix = ['st','nd','rd',...Array(13).fill('th'),'st','nd','rd',Array(7).fill('th'),'st']
  let dayNames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

  let dayIndex = date.getDate();
  let monthIndex = date.getMonth();
  let year = date.getFullYear();

  return dayNames[dayIndex] + ', ' + monthNames[monthIndex] + ' ' + dayIndex + suffix[dayIndex-1] + ' ' + year;
}

let date = new Date()

console.log(convertDateToString(date));

// wanted format: Thursday, May 2nd 2019

答案 3 :(得分:1)

值得一提的是,每次处理日期时,都值得考虑添加Moment.js-这是一个使日期处理变得更加简单的库。

您可以通过以下方式设置显示格式:

function convertDateToString(date) {
  return moment(date)
    .format("dddd, MMMM Do YYYY")
}

let date1 = new Date("2019-05-01T10:00:00")
let date2 = new Date("2019-05-02T10:00:00")
let date3 = new Date("2019-05-03T10:00:00")
let date4 = new Date("2019-05-04T10:00:00")

console.log(convertDateToString(date1));
console.log(convertDateToString(date2));
console.log(convertDateToString(date3));
console.log(convertDateToString(date4));

// wanted format: Thursday, May 2nd 2019
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

有关更多格式设置选项,you can check the documentation