2

I am beginner in java script i tried to show time as "AM" & "PM" using if else condition. It works but the problem is at time of 12 am or 12 pm it always show "0 am" and "0 pm". Can any one tell me where i am doing mistake. my code is

const today = new Date();
const day = today.getDay();
const dayList = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

document.getElementById("date").innerHTML = `Today is : ${dayList[day]}.`;

let hour = today.getHours();

const minute = today.getMinutes();
const second = today.getSeconds();

let prepand = (hour >= 12) ? " PM " : " AM ";

hour = (hour >= 12) ? hour - 12 : hour;

if (hour === 12 && prepand === ` PM` && minute === 0 && second === 0) {
  document.getElementById("time").innerHTML = `Current Time is : ${hour}${prepand} : ${minute} : ${second}`;
} else {
  document.getElementById("time").innerHTML = `Current Time is : ${hour}${prepand} : ${minute} : ${second}`;
}
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47
  • The code inside the two branches of the `if` statement is exactly the same, why do you think it should behave differently? – 6502 Apr 11 '20 at 07:16
  • 1
    You should use [`Date#toLocaleTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString) instead. – str Apr 11 '20 at 07:23
  • toLocaleTimeString() may behave differently based on region / location. – Khurram Ishaque Apr 11 '20 at 07:25

2 Answers2

0

You are kind of over complicating this. Javascript has a way to get the long day name and 12 hour format natiely.

// just to update the time
window.setInterval(function() {

  let d = new Date();
  document.getElementById("date").innerHTML = `Today is : ${d.toLocaleDateString('en-GB', {weekday: 'long'})}.`;
  document.getElementById("time").innerHTML = `Current Time is : ${d.toLocaleString('en-GB', { hour: 'numeric', hour12: true })} : ${d.getMinutes()} : ${d.getSeconds()}`;

}, 1000); // every second
<p id=date></p>
<p id=time></p>
Fraser
  • 15,275
  • 8
  • 53
  • 104
0

As others have pointed out, there are simpler ways to do this, and the problem is not a new one.

However in the interests of learning, of course you want to know what is wrong with your own code, so let's solve it! The issue is this line:

hour = (hour >= 12) ? hour - 12 : hour;

If the time is 12 (am or pm), this sets hour to 0. The fix is simple, subtract 12 only when hour is greater than 12:

hour = (hour > 12) ? hour - 12 : hour;

Working JSFiddle (hardcodes hour to 12 to test).

Don't Panic
  • 13,965
  • 5
  • 32
  • 51