Javascript 将“getHours()”方法的 1-24 小时更改为 1-12 小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10556879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:51:06  来源:igfitidea点击:

Changing the 1-24 hour to 1-12 hour for the "getHours()" Method

javascripttimehour

提问by Tony Wilkerson

When I use the "getHour()" method in javascript, it displays the military time format. I need it to display the hour in numbers between 1-12 instead. Can anybody tell me how to do this? Here is the code I am using:

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

回答by mcw

Why not do it the brief way? Math, people! :)

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

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

回答by Alnitak

This will correct 13 - 24 back to the range 1 - 12, and 0 back to 12:

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

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

Also, you need to stop repeating yourself in your code. Call time.getHours()and time.getMinutes()and store their values just onceeach, and thenworry about adding the leading zeroes, e.g.:

此外,您需要停止在代码中重复自己。每次调用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;
}

回答by Baraskar Sandeep

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;
}

This Function will give the perfect time format in 1-12 hours

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

回答by falero80s

Other answers are indeed very good. But I think, following can be included too.

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

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
    }

See what I did there in arrayHrs ;)

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

回答by mahde amar

the easy way to use this.

使用它的简单方法。

setInterval(function() {

var d = new Date();

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

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

回答by chickens

Shortest:

最短:

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

If you need padding with 0:

如果你需要用 0 填充:

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

Another option, also with AM & PM:

另一种选择,也有 AM 和 PM:

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

回答by Hamza Murtaza

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)
}

回答by William Herrmann

An answer similar to the accepted, but without the ||operator.

一个类似于接受的答案,但没有||运营商。

Purely arithmetical:

纯算术:

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

Test it here. Simulating hours 0 - 23:

在这里测试一下。模拟 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>