【问题标题】:Ordinal for day of the week星期几的序数
【发布时间】:2021-06-17 19:32:54
【问题描述】:

我想像下面这样格式化日期

Tuesday, 2nd day of the week

到目前为止,我已经完成了

console.log(moment().format("dddd, Eo [day of the week]"))

无法添加“Eo”以获得序数。它不格式化'o',打印为Sunday, 7o day of the week

我怎样才能完成这项工作。

【问题讨论】:

  • 你应该用Do代替Eo
  • @ashiish.me 不是 Do 一个月的一天吗?我想要星期几
  • 啊,我现在明白了,你只想要第 1 到第 6?
  • 您可以查看更新后的答案,它应该是小写的。

标签: javascript momentjs moment-timezone


【解决方案1】:

使用do all small,以便返回从第 0 到第 6 的所有序数。

console.log(moment().format("dddd, do [day of the week]"))

另外,E 返回不带序号的星期几。

更新:

似乎do 我认为该解决方案仍然不适用,因为0th 而不是1st

这是可以自定义日期的自定义实现。

const customizedDayWithOrdinal = input => {
  const [dayName, day] = input.split(',');
  const number = Number(day.trim()) % 10;

  const ordinal = (~~ (number % 100 / 10) === 1) ? 'th' :
            (number === 1) ? 'st' :
            (number === 2) ? 'nd' :
            (number === 3) ? 'rd' : 'th';
  return `${dayName}, ${number}${ordinal} of the week`;
}

console.log(customizedDayWithOrdinal(moment().format(`dddd, E`)))

sn-p 来自moment.js doc 的示例。

参考:Customize Ordinal

【讨论】:

    【解决方案2】:

    moment 使用的格式是 do。 你可以看看文档

    https://momentjs.com/docs/#/displaying/format/

    【讨论】:

      【解决方案3】:

      MomentJs 不提供 Eo 的格式,只提供 Do。但是您仍然可以使用自己的函数附加序数,如下所示:

          const addOrdinal = (num) => {
              switch(num){
                  case 1:
                      return num + 'st'
                  break
                  case 2:
                      return num + 'nd'
                  break
                  case 3:
                      return num + 'rd'
                  break
                  default:
                      return num + 'th'
              }
          }
      
          const day = moment().format(`dddd`)
          const dayOfWeek = addOrdinal(moment().format('E'))
      
          console.log(`${day}, ${dayOfWeek} day of the week `)
      
      

      CodePen demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-31
        • 1970-01-01
        • 1970-01-01
        • 2014-06-26
        相关资源
        最近更新 更多