【发布时间】:2017-12-27 17:54:57
【问题描述】:
我有这个用于显示时间(根据时区)和日期的 Javascript 代码,但问题在于 AM/PM。它不会随着时间的变化而自动更新;经过多次尝试,我未能自动更新,因此在这里寻求帮助。下面是代码:
$(document).ready(function(){
// Create two variable with the names of the months and days in an array
// Count 3 variable for months
var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var dayNames= ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
// Create a newDate() object
var newDate = new Date();
// Extract the current date from Date object
newDate.setDate(newDate.getUTCDate());
// Output the day, date, month and year
$('#Date').html(/*dayNames[newDate.getUTCDay()] + " " + */monthNames[newDate.getMonth()] + ' ' + newDate.getDate() + ', ' + newDate.getFullYear());
setInterval( function() {
// Create a newDate() object and extract the seconds of the current time on the visitor's
var seconds = new Date().getUTCSeconds();
// Add a leading zero to seconds value
$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);
},1000);
setInterval( function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getUTCMinutes();
// Add a leading zero to the minutes value
$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
},1000);
setInterval( function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getUTCHours();
var ampm = 'AM';
if(hours > 5)
{
hours -= 5; // Time Zone
ampm = 'AM'; // AM/PM According to Time Chosen
}
else if(hours == 5)
{
ampm = 'PM';
};
// Add a leading zero to the hours value
$("#hours").html(( hours < 10 ? "0" : "" ) + hours);
$("#ampm").html(ampm);
}, 1000);
});
<span id="hours"></span>:<span id="min"></span> <span id="ampm"></span> <span id="Date"></span>
【问题讨论】:
-
请注意,
newDate.setDate(newDate.getUTCDate());可能会更改日期,因为 UTC 日期并不总是与本地日期相同。为什么要使用 UTC 值然后减去 5?您是否尝试将日期设置为不同的时区?已经有很多问题了。
标签: javascript date time format