How to get AM or PM?

You should just be able to check if hours is greater than 12.

var ampm = (hours >= 12) ? "PM" : "AM";

But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.


const now = new Date()
      .toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
      .toLowerCase();

Basically you just need to put {hour12: true} and it's done.

result => now = "21:00 pm";


Try below code:

$('#btnToronto').click(function () {
    var hours = new Date().getHours();
    var hours = (hours+24-2)%24; 
    var mid='am';
    if(hours==0){ //At 00 hours we need to show 12 am
    hours=12;
    }
    else if(hours>12)
    {
    hours=hours%12;
    mid='pm';
    }
    alert ('Toronto time: ' + hours + mid);
});

You can use like this,

var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');

Hopes this will be better with minutes too.