Mar*_*Tan 5 javascript timezone date
我目前正在尝试开发一个倒数计时器页面。这是倒数计时器代码:
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date("July 01, 2015 22:00:00");
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
if(diff < 0){
// Instantiate a countdown FlipClock
clock = $('.clock').FlipClock(0, {
clockFace: 'DailyCounter',
countdown: true
});
$('.message').html('Lets Go!!');
$('.Go').removeAttr("disabled");
$( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
}
else{
// Instantiate a countdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
callbacks: {
stop: function() {
$('.message').html('Lets Go!!');
$('.Go').removeAttr("disabled");
$( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
}
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
问题是倒计时时间因时区而异。例如,澳大利亚用户的倒计时时间将比马来西亚用户 (GMT+8) 的倒计时时间短三小时。
如何将初始倒计时日期的时区标准化/设置为 GMT+8,以便不同时区的用户具有相同的倒计时时间?
根据我们的讨论,此示例代码可将任何时区时间转换为 UTC+8 时区时间。
var d = new Date();
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000 /* convert to UTC */ + (/* UTC+8 */ 8) * 60 * 60 * 1000);
console.log('UTC+8 Time:', d);
Run Code Online (Sandbox Code Playgroud)
这里有一个JSFiddle可供参考。
虽然控制台输出显示日期对象的时区不是 UTC+0800,但它们的日期值(年、月、日等)已全部转换为 UTC+0800 时间。
只是无法编辑日期对象的实际时区,但可以编辑其日期值以反映新时区,这就是我们在这里所做的。
| 归档时间: |
|
| 查看次数: |
15609 次 |
| 最近记录: |