将javascript中的gethours更改为1-12

时间:2014-03-25 03:19:25

标签: javascript

我试图在javascript中使用gethours()方法,但它不断返回军事时间。有人可以帮我修理它,以便显示时钟时间吗? (1-12)。非常感谢你!

// Reroute from the conf.js script
var chat = $( '.chat-output' ),

    message = function ( message, userId ) {
        var dt = new Date(),
            time = dt.getHours() + ":" + dt.getMinutes(); // + ":" + dt.getSeconds();

        return $( '<div class="chat-message color-' + users[userId] + '">' +
                    '<div class="chat-id color-' + users[userId] + '"></div>' +
                    '<div class="chat-user-message">' + message + '</div>' +
                    '<div class="chat-time">' + time + '</div>' +
                '</div>' );
    },

    addText = function ( text ) {
        // log.innerHTML += text;
        // log.scrollTop = log.scrollHeight;

        console.log( text );
    },

    addRemoteText = function ( userId, text ) {
        // addText( '[' + userId + ']: ' + text+'<br>' );

        chat.append( message( text, userId ) );
        chat.scrollTop( chat.get( 0 ).scrollHeight );
    };

3 个答案:

答案 0 :(得分:0)

这样的东西?

var dt = new Date();
var hours = dt.getHours();
var ampm = hours > 11 ? 'PM' : 'AM';
if (hours > 12) {
    hours -= 12;
} else if (hours === 0) {
    hours = 12;
}
var time = hours + ":" + dt.getMinutes() + ' ' + ampm;

Fiddle

答案 1 :(得分:0)

function ampm(date){
    var dt= date || new Date, 
    h= dt.getHours(), 
    m= dt.getMinutes(), 
    s= dt.getSeconds(), 
    ampm;

    if(h>12){
        h-= 12;
        ampm= (h%12)? ' PM': ' AM';
    }
    else ampm= (h%12)? ' AM': ' PM';

    m= m<10? '0'+m: m;
    s= s<10? '0'+s: s;
    return [h, m, s].join(':')+ampm;
}

<强> AMPM()

/*  returned value: (String)
11:52:55 PM
*/

答案 2 :(得分:0)

以下是以12小时格式格式化时间的另一个版本:

// Returns formatted time for given Date object, or
// current system time if d is falsey.
function getTime(d) {
  d = d || new Date();
  var hrs = d.getHours();
  var pad = function(n){return (n<10?'0':'')+ +n};
  return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) + ' ' + (hrs<12? 'AM':'PM');
}

console.log(getTime(new Date(2014,2,24, 0, 5))); // 12:05 AM
console.log(getTime(new Date(2014,2,24,10,25))); // 10:25 AM
console.log(getTime(new Date(2014,2,24,20,15))); // 08:15 PM

请注意,在许多情况下,首选24小时是为了避免异常情况,例如凌晨12:00(实际上既不是上午或下午),也就是凌晨00:00凌晨01:00之前。