将"getHours()"方法更改为1-24小时至1-12小时

Ton*_*son 18 javascript time hour

当我在javascript中使用"getHour()"方法时,它会显示军事时间格式.我需要它来显示1-12之间的小时数.谁能告诉我怎么做?这是我正在使用的代码:

function updateclock()
{

    var time = new Date();
    var todisplay = '';

    if (time.getHours() < 10) todisplay += time.getHours();
    else todisplay += time.getHours();

    if (time.getMinutes() < 10) todisplay += ':0' + time.getMinutes();
    else todisplay += ':' + time.getMinutes();

    document.getElementById("clock").innerHTML = todisplay;
}
Run Code Online (Sandbox Code Playgroud)

mcw*_*933 38

为什么不以简短的方式做呢?数学,人!:)

// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
Run Code Online (Sandbox Code Playgroud)

  • 数学在哪里!(X + n*12)%12 ==> X%12缩短你的答案.function hours12(date){return date.getHours()%12 || 12; } (5认同)

Aln*_*tak 32

这将使13 - 24恢复到1 - 12的范围,并将0更改为12:

var hours = time.getHours();
if (hours > 12) {
    hours -= 12;
} else if (hours === 0) {
   hours = 12;
}
Run Code Online (Sandbox Code Playgroud)

此外,您需要停止在代码中重复自己.通话time.getHours()time.getMinutes()和存储他们的价值观只是一次每一个,并担心添加前导零,例如:

function updateclock() {

    function pad(n) {
         return (n < 10) ? '0' + n : n;
    }

    var time = new Date();
    var hours = time.getHours();
    var minutes = time.getMinutes();

    if (hours > 12) {
        hours -= 12;
    } else if (hours === 0) {
        hours = 12;
    }

    var todisplay = pad(hours) + ':' + pad(minutes);
    document.getElementById("clock").innerHTML = todisplay;
}
Run Code Online (Sandbox Code Playgroud)


Bar*_*eep 8

function getClockTime(){
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour + ':' + minute + ':' + second + " " + ap;
   return timeString;
}
Run Code Online (Sandbox Code Playgroud)

此功能将在1-12小时内提供完美的时间格式


chi*_*ens 5

最短:

const hours12 = date => (date.getHours() % 12  || 12);
Run Code Online (Sandbox Code Playgroud)

如果需要用 0 填充:

const hours12 = date => ("0"+(date.getHours() % 12  || 12)).slice(-2);
Run Code Online (Sandbox Code Playgroud)

另一种选择,也适用于 AM 和 PM:

const hours12 = date => date.toLocaleString('en-US', { hour: 'numeric', hour12: true })
Run Code Online (Sandbox Code Playgroud)