简体   繁体   中英

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>

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.

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`;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM