How to get AM or PM?

后端 未结 11 1216
伪装坚强ぢ
伪装坚强ぢ 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 19:58

    with date.js

    <script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
    

    you can write like this

    new Date().toString("hh:mm tt")
    

    cheet sheet is here format specifiers
    tt is for AM/PM

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

    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.

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

    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.

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

    The best way without extensions and complex coding:

    date.toLocaleString([], { hour12: true});
    

    How do you display javascript datetime in 12 hour AM/PM format?

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

    Try this:

    h = h > 12 ? h-12 +'PM' : h +'AM';
    
    0 讨论(0)
  • 2020-12-08 20:15

    If hours is less than 12, it's the a.m..

    var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
        am;
    // adjust for timezone
    hours = (hours + 24 - 2) % 24;
    // get am/pm
    am = hours < 12 ? 'a.m.' : 'p.m.';
    // convert to 12-hour style
    hours = (hours % 12) || 12;
    

    Now, for me as you didn't use getUTCHours, it is currently 2 hours after

    hours + ' ' + am; // "6 p.m."
    
    0 讨论(0)
提交回复
热议问题