-1

I am using new Date() to create a customize time, and also I'm using a function to format time in am/pm:

const formatTimeAMPM = (date, midnight = { am: "AM", pm: "PM" }) => {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? "0" + minutes : minutes;
  hours = hours < 10 ? "0" + hours : hours;
  var strTime = hours + ":" + minutes + " " + ampm;
  return strTime;
};

let startDate = new Date(Date.now());
console.log('before change :',formatTimeAMPM(startDate));
startDate.setHours(8, 30, 0, 0);
console.log('after change :',formatTimeAMPM(startDate));

If you run the snippet, you will see console logs the 8:30 pm , Can anyone tell me how to set am for it when I change hour the startDate ?

Hamid Shoja
  • 3,838
  • 4
  • 30
  • 45

1 Answers1

1

Your am/pm check is backwards:

var ampm = hours >= 12 ? ` ${midnight.am}` : ` ${midnight.pm}`;

If the hour is >= 12, it should be PM not AM, so it should be:

var ampm = hours >= 12 ? ` ${midnight.pm}` : ` ${midnight.am}`;

Now if you run it, it will show 8:30 AM and if you set the hour to 20 it will show 8:30 PM

This will fix your current issue but it would be better to use an existing library for date formatting since it can get complicated, especially with i18n. There a couple popular ones such as date-fns and moment.js that will do the heavy lifting for you.

smashed-potatoes
  • 2,068
  • 1
  • 13
  • 17
  • The function works as well, and I've used it elsewhere, my question is about how to set am when I change the hour and minutes – Hamid Shoja Feb 12 '20 at 20:41
  • 1
    Hour `8` is 8 AM so the logic should be inversed. If you simply want to show 8 AM with your current logic, you would set the hour to `20`, i.e.: `startDate.setHours(20, 30, 0, 0);`. – smashed-potatoes Feb 12 '20 at 20:42