23

当我在 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;
}
4

10 回答 10

46

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

// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
于 2014-07-17T13:42:19.077 回答
33

这会将 13 - 24 校正回 1 - 12 的范围,并将 0 校正回 12:

var hours = time.getHours();
if (hours > 12) {
    hours -= 12;
} else if (hours === 0) {
   hours = 12;
}

此外,您需要停止在代码中重复自己。每次调用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;
}
于 2012-05-11T18:42:57.970 回答
9
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;
}

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

于 2014-02-26T09:04:50.310 回答
3

其他答案确实很好。但我认为,也可以包括以下内容。

var d = new Date();
var hour = d.getHours(); 
var minute = d.getMinutes();
var fulltime = "";

// create a 24 elements(0-23) array containing following values
const arrayHrs = [12,1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11];

    // since getMinutes() returns 0 to 9 for upto 9 minutes, not 00 to 09, we can do this
    if(minute < 10) {
        minute = "0" + minute;
    }

    if( hour < 12) {
        // Just for an example, if hour = 11 and minute = 29
        fulltime = arrayHrs[hour] + ":" + minute + " AM"; // fulltime = 11:29 AM
    }
    else {
        // similarly, if hour = 22 and minute = 8
        fulltime = arrayHrs[hour] + ":" + minute + " PM"; // fulltime = 10:08 PM
    }

看看我在 arrayHrs 中做了什么;)

于 2017-06-26T01:23:18.977 回答
2

最短:

const hours12 = date => (date.getHours() % 12  || 12);

如果您需要使用 0 填充:

const hours12 = date => ("0"+(date.getHours() % 12  || 12)).slice(-2);

另一个选项,还有 AM & PM:

const hours12 = date => date.toLocaleString('en-US', { hour: 'numeric', hour12: true })
于 2020-04-06T04:36:09.807 回答
1

使用它的简单方法。

setInterval(function() {

var d = new Date();

document.getElementById("demo").innerHTML = 
d.getHours() % 12+" : "+d.getMinutes()+" : "+d.getSeconds();

}, 1000);
<p id="demo" ></p>

于 2018-02-09T08:51:17.677 回答
0

这会将 24h 时间转换为 12h,并添加 AM 和 PM 后缀。

const hours12 = (date) => {
    let ampm = date.getHours() >= 12 ? 'pm' : 'am';
    return `${(date.getHours() % 12  || 12)} ${ampm}`;
};
console.log(hours12(new Date()));

@chickens 的修改版本。

于 2021-03-16T07:00:02.317 回答
0

类似于接受的答案,但没有||运算符。

纯算术:

// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 11) % 12 + 1; }

在这里测试一下。模拟 0 - 23 小时:

var demoTable = document.getElementById("demo");

// simulate getHours() values 0-23
for (i = 0; i < 24; i++) {
  var row = demoTable.insertRow(-1);
  var format24Cell = row.insertCell(0);
  var conversionCell = row.insertCell(1);
  var format12Cell = row.insertCell(2);
  format24Cell.innerHTML = i;
  conversionCell.innerHTML = "( <b>" + i + "</b> + 11) % 12 + 1 =";
  
  // conversion takes place here
  format12Cell.innerHTML = (i + 11) % 12 + 1;
}
table {
  border-collapse: collapse;
  width: 100%;
}

table,
th,
td {
  border: 1px solid black;
}

th {
  padding: 0, 5px
}

td {
  padding-left: 5px;
}
<table id="demo">
  <tr>
    <th colspan="3">24 to 12 Hour Format Conversion Demo</th>
  <tr>
  <tr>
    <th>24 Hour Format</th>
    <th>Conversion</th>
    <th>12 Hour Format</th>
  </tr>
</table>

于 2019-08-09T01:49:48.003 回答
0

这可以使用 .getHours() 函数轻松实现。请记住,getHours 返回 0 到 23 之间的整数值,因此您所要做的就是检查 0 值

let date = new Date()
let hour = (date.getHours()===0)? 24:date.getHours()

于 2021-08-04T16:27:13.040 回答
0
getDateTime = () => {
    const today = new Date();
    const day = today.toLocaleDateString('en-us', { weekday: 'short' });
    const month = today.toLocaleString('en-us', { month: 'short' });
    const date = today.getDate()
    const year = today.getFullYear()
    const hours = today.getHours()
    const minutes = today.getMinutes().toString()
    var dayORnight = "AM";
    if (hours > 11) { dayORnight = "PM"; }
    if (hours > 12) { hours = hours - 12; }
    if (hours == 0) { hours = 12; }
    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }

    const datetime = `${day}, ${month} ${date}, ${year} at ${hours}:${minutes} ${dayORnight}`;
    console.log(datetime)
}
于 2019-01-14T05:58:06.557 回答