How to display the time of day with moment.js?

How would I display something like "Sunday Morning" if it’s before 12pm or "Sunday Afternoon" if it’s after 12pm?

I’m using the below to get the current day

var now = moment().format("dddd");
$("#date").append(now);
<span id="date"></span>

2 thoughts on “How to display the time of day with moment.js?”

  1. Moment.js unfortunately doesn’t have a built-in token for morning/afternoon/evening, but you can fake it.

    const [day, hour, am_pm] = moment().format("dddd,h,A").split(",");
    let dateOut;
    
    if (am_pm === 'AM') {
      dateOut = `${day} morning`;
    } else {
      if (hour >= 12 && hour < 6) {
        dateOut = `${day} afternoon`;
      } else {
        dateOut = `${day} evening`;
      }
    }
    
    Reply
  2. Something like this will probably do the trick:

    console.log(`${moment().format("dddd")} ${(moment().format("a") === 'am' ? ' Morning' : 'Afternoon')}`)
    

    Please note that moment.js is being phased out and is not recommended for use in new projects.

    Reply

Leave a Comment