Categories
JavaScript Answers

How to output text based on user’s current time with JavaScript?

Spread the love

Sometimes, we want to output text based on user’s current time with JavaScript.

In this article, we’ll look at how to output text based on user’s current time with JavaScript.

How to output text based on user’s current time with JavaScript?

To output text based on user’s current time with JavaScript, we can use the JavaScript date’s getHours method to get the hour of the day.

Then we can use an if statement to output text according to the hour of the day.

For instance, we write:

const today = new Date()
const curHr = today.getHours()

if (curHr < 12) {
  console.log('good morning')
} else if (curHr < 18) {
  console.log('good afternoon')
} else {
  console.log('good evening')
}

We get the current date and time with new Date().

Then we get the hour of the current date and time with getHours.

Finally, we use an if-else statement to check for the hour.

If it’s less than 12, then it’s morning.

If it’s less than 18, then it’s afternoon.

Otherwise, it’s evening.

Conclusion

To output text based on user’s current time with JavaScript, we can use the JavaScript date’s getHours method to get the hour of the day.

Then we can use an if statement to output text according to the hour of the day.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *