How to get AM or PM?

后端 未结 11 1215
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 19:38

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.

$(\'#btnToronto\').click(function () {
    var hours = ne         


        
相关标签:
11条回答
  • 2020-12-08 20:15
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var timewithampm = hours + ':' + minutes + ' ' + ampm;
    return timewithampm;
    
    0 讨论(0)
  • 2020-12-08 20:16
    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";

    0 讨论(0)
  • var dt = new Date();
    var h = dt.getHours(),
      m = dt.getMinutes();
    var time;
    if (h == 12) {
      time = h + ":" + m + " PM";
    } else {
      time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
    }
    //var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
    
    console.log(`CURRENT TIME IS ${time}`);
    

    This will work for everytime,

    0 讨论(0)
  • 2020-12-08 20:23

    very interesting post. in a function that take a date in parameter it can appear like that :

    function hourwithAMPM(dateInput) {
       var d = new Date(dateInput);
       var ampm = (d.getHours() >= 12) ? "PM" : "AM";
       var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
    
       return hours+' : '+d.getMinutes()+' '+ampm;
    
    }
    
    0 讨论(0)
  • 2020-12-08 20:25

    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);
    });
    
    0 讨论(0)
提交回复
热议问题