Possible Duplicate:
Formatting a date in JavaScript
How to get datetime in javascript?
我找到了一个显示不同时区的当前日期和时间的脚本。我不知道如何更改格式。目前,它显示为 MM/DD/YYYY HH:MM:SS AM/PM
我希望它只显示为 HH:MM AM/PM
我对 jQuery 的熟练程度比纯 JavaScript 的熟练程度更高,这让我很困惑:
$(document).ready(function() {
function calcTime(offset) {
currentDate = new Date();
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000);
newDate = new Date(utc + (3600000*offset));
return newDate.toLocaleString();
}
function displayTimes() {
$("#chicago").html(calcTime("-6"));
$("#london").html(calcTime("+1"));
$("#shanghai").html(calcTime("+8"));
};
window.setInterval(displayTimes, 1000);
});
最佳答案
罪魁祸首是以下行。
return newDate.toLocaleString();
具体来说,toLocaleString()
您可以在此处了解有关该行功能的更多信息:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
一种快速方法是使用 .toTimeString()
您不想返回 newDate.toLocaleString() 或 .toTimeString(),而是希望使其按您希望的方式打印。
例如
return newDate.getHours() + ':' newDate.getMinutes();
这会给你军事时间。
如果您想要上午/下午显示,这可以为您实现
(newDate.getHours() > 11) ? 'pm' : 'am'
如果你想要美化时间,0 是午夜 12 点,12 是中午。如果小时数大于12,则可以减去12。如果为0,也可以将其设置为显示12。所有这些都可以这样做:
(newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours());
绝对应该对 newDate.getHours() 使用 var。说到变量...
请重新格式化您的变量: var 当前日期 = 新日期(), UTC = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000), newDate = new Date(utc + (3600000*offset));
希望有帮助。
编辑:现在一起: 替换以下内容
return newDate.toLocaleString();
具有以下内容
return (newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours()) + ' : ' + newDate.getMinutes() + ' ' + (newDate.getHours() > 11) ? 'pm' : 'am';
这相当草率,而且写得很匆忙,但是如果你对 newDate.getHours() 使用 var ,那么它会更容易阅读。
谢谢。
关于javascript - 调整 JavaScript 日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14634244/