bula
bula

Reputation: 9419

Ordinal for day of the week

I want to format the date like below

Tuesday, 2nd day of the week

So, far I have done

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

Cannot add 'Eo' to get ordinal. It does not format 'o', print as Sunday, 7o day of the week

How can I get this done.

Upvotes: 1

Views: 628

Answers (3)

Ashish Yadav
Ashish Yadav

Reputation: 2008

Use do all small so that it returns all the ordinal from 0th to 6th.

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

Also, E returns Day of week without ordinal.

Update:

It seems with do I think the solution is still not applicable because of 0th rather than 1st.

Here's the custom implementation that can customize the date.

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`)))

The snippet is from the example of moment.js doc.

Reference: Customize Ordinal

Upvotes: 1

Isaac Yong
Isaac Yong

Reputation: 109

MomentJs doesn't provide the format of Eo, only Do. But you can still append the ordinal using your own function like so:

    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

Upvotes: 0

Radowan Mahmud Redoy
Radowan Mahmud Redoy

Reputation: 271

The format which moment is using is do. You can have a look at the documentation

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

Upvotes: 1

Related Questions