Advertisement
satishfrontenddev5

Untitled

Feb 18th, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. display a message based on the time of the day in javascript?
  2.  
  3. You can display a message based on the time of the day in JavaScript using the `Date` object to get the current hour. Here's how you can do it:
  4.  
  5. ```javascript
  6. function getMessageByTime() {
  7.    const hour = new Date().getHours();
  8.  
  9.    if (hour >= 5 && hour < 12) {
  10.        return "Good morning!";
  11.    } else if (hour >= 12 && hour < 18) {
  12.        return "Good afternoon!";
  13.    } else {
  14.        return "Good evening!";
  15.    }
  16. }
  17.  
  18. // Example usage
  19. const message = getMessageByTime();
  20. console.log(message); // Output depends on the current time of the day
  21. ```
  22.  
  23. In this code:
  24. - We create a function `getMessageByTime` that determines the current hour using `new Date().getHours()`.
  25. - Based on the hour, we return different messages for morning, afternoon, and evening.
  26. - We then call the function and store the message in a variable, and finally log the message to the console.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement