Skip to content

Show good morning, good night depending on the time in JavaScript

Show good morning, good night depending on the time in JavaScript — You would have seen websites greeting their visitors with a message that says Good morning, good afternoon or good evening, depending upon the time they visit the website. You can add a message on your html web page greeting the visitor depending on the time of the day with a simple script.

Setting to the element directly

<label id="greeting"></label>

<script>
    var myDate = new Date();
    var currentHour = myDate.getHours();

    var msg;

    if (currentHour < 12)
        msg = 'Good Morning';
    else if(currentHour == 12)
	msg = 'Good Noon';
    else if (currentHour >= 12 && currentHour <= 17)
        msg = 'Good Afternoon';
    else if (currentHour >= 17 && currentHour <= 24)
        msg = 'Good Evening';

    document.getElementById('greeting').innerHTML =
        '<b>' + msg + '</b>';
</script>

Using document.write()

<script type="text/javascript">
        document.write("<center><font size=+3 style='color: green;'>");
        var day = new Date();
        var currentHour = day.getHours();
        if (currentHour >= 0 && currentHour < 12) {
            document.write("Good Morning!");
        } else if (currentHour == 12) {
            document.write("Good Noon!");
        } else if (currentHour >= 12 && currentHour <= 17) {
            document.write("Good Afternoon!");
        } else {
            document.write("Good Evening!");
        }
        document.write("</font></center>");
    </script>

TypeScript

When you are using TypeScript, you can call the script inside ngOnInit() method.

ngOnInit() {
    var myDate = new Date();
    var hrs = myDate.getHours();

    var greet;

    if (hrs < 12)
        greet = '🌅 GOOD MORNING';
    else if (hrs >= 12 && hrs <= 17)
        greet = '🌞 GOOD AFTERNOON';
    else if (hrs >= 17 && hrs <= 24)
        greet = '🌇 GOOD EVENING';

    document.getElementById('greeting').innerHTML =
        '<b>' + greet + '</b>!';      

  }

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.