Fernandez Abby
Fernandez Abby

Reputation: 33

How to display Good Morning/Afternoon/Evening using javascript in 12hours format

It is 4:11PM here now but my output is shown as 'Good Morning' - why is this happening?

$(document).ready(function() {
  function dateTime() {
    var ndate = new Date();
    var h = ndate.getHours() % 12;
    var format = h >= 12 ? 'PM' : 'AM';
    var m = ndate.getMinutes().toString();
    var s = ndate.getSeconds().toString();

    if (h < 12) {
      h = "0" + h;
      $("h3.day-message").html("Good Morning");
    } else if (h < 18) {
      $("h3.day-message").html("Good Afternoon");
    } else {
      $("h3.day-message").html("Good Evening");
    }

    if (s < 10) {
      s = "0" + s;
    }

    if (m < 10) {
      m = "0" + m;
    }

    $('.date').html(h + ":" + m + ":" + s + format);
  }

  setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>

Upvotes: 3

Views: 12565

Answers (5)

Shohedul
Shohedul

Reputation: 213

Display Good Morning/Afternoon/Evening using javascript in 12hours format

const displayGreeting =()=>{

    const myDate = new Date();
    const hrs = myDate.getHours();
    let 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';
        return  greet
  }

Upvotes: 0

mplungjan
mplungjan

Reputation: 177691

Without jQuery

const messages = [
  { ampm: "am", "greet": 'Good Morning' },
  { ampm: "pm", "greet": 'Good Afternoon' },
  { ampm: "pm", "greet": 'Good Evening' }
];

window.addEventListener("DOMContentLoaded", () => {
  const dateSpan = document.getElementById("date");
  const message = document.getElementById("day-message");
  const dateTime = () => {
    let now = new Date(),
      hour = now.getHours(),
      hh = hour % 12, // (hour % 12).toString().padStart(2,"0") if you want leading 0
      mm = now.getMinutes().toString().padStart(2,"0"),
      ss = now.getSeconds(),
      period = 0;

    if (hour < 12) period = 0;
    else if (hour >= 12 && hour < 17) period = 1;
    else if (hour >= 17 && hour <= 24) period = 2;
    message.textContent = messages[period].greet;
    dateSpan.textContent = `${hh}:${mm}${messages[period].ampm}`; 

  };
  setInterval(dateTime, 500);
});
<h3 id="day-message"></h3>
<span id="date"></span>

Upvotes: 0

Krishna Soni
Krishna Soni

Reputation: 95

$(document).ready(function() {
  function dateTime() {
  var format="";
    var ndate = new Date();
	var hr = ndate.getHours();
    var h = hr % 12;
	
	 if (hr < 12)
	 {
        greet = 'Good Morning';
		format='AM';
		}
    else if (hr >= 12 && hr <= 17)
	{
        greet = 'Good Afternoon';
		format='PM';
		}
    else if (hr >= 17 && hr <= 24)
        greet = 'Good Evening';
	
    var m = ndate.getMinutes().toString();
    var s = ndate.getSeconds().toString();

    if (h < 12) {
      h = "0" + h;
      $("h3.day-message").html(greet);
    } else if (h < 18) {
      $("h3.day-message").html(greet);
    } else {
      $("h3.day-message").html(greet);
    }

    if (s < 10) {
      s = "0" + s;
    }

    if (m < 10) {
      m = "0" + m;
    }

    $('.date').html(h + ":" + m + ":" + s + format);
  }

  setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>

Upvotes: 2

Mesar ali
Mesar ali

Reputation: 1898

You are calculating mode, so h will never be greater that 12

So, Instead of

var h = ndate.getHours() % 12;

Use it

var h = ndate.getHours();

Explaination: modulo operator(%) will divide total hours by 12 and return the Remainder. For example if current time is 4 pm, I'll be 16 hours, so It'll return 4

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you are using the modulo operator. This means that your h > 12 check will never be hit as the remainder of the division cannot be greater than 12. It's because of this your logic always believes it's still the morning. To fix this, just use a simple < check when comparing the hour figure.

Also note that you have some issues with the formatting of the date, such as appending extra zeroes so you end up with 011 as hour values. You can fix this by using slice().

With all that said, try this:

$(document).ready(function() {
  function dateTime() {
    var ndate = new Date();
    var hours = ndate.getHours();
    var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
    $("h3.day-message").text(message);

    $('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
  }

  setInterval(dateTime, 1000);
});

Number.prototype.leadingZeroes = function(len) {
  return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>

Upvotes: 4

Related Questions