Know if it's morning, afternoon, evening or night in JavaScript

To know if it's morning, afternoon, evening or night in JavaScript, you can use the getHours() function (returns the hour between 0 and 23):

javascript
let now = new Date();

let isMorning   = now.getHours() > 5  && now.getHours() <= 12;
let isAfternoon = now.getHours() > 12 && now.getHours() <= 18;
let isEvening   = now.getHours() > 18 && now.getHours() <= 22;
let isNight     = now.getHours() > 22 || now.getHours() <= 5;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.