当我用“getHour()”方法在JavaScript中,它显示的时间格式。 我需要它在数字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;
}
为什么不这样做短暂的方法是什么? 数学,人! :)
// returns the hours number for a date, between 1 and 12
function hours12(date) { return (date.getHours() + 24) % 12 || 12; }
这将纠正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;
}
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小时的最佳时机格式
其他的答案确实是很不错的。 但我认为,以下可以包含太多。
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那里做;)
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)
}