I have a jquery function that uses moment.js to calculate time in different timezone based on the clock in the client's system:
function updateTime(){
var chicago = moment.tz("America/Chicago").format('h:mm:ss A');
$('#time').html( chicago +", ");
};
moment.tz.add('America/Chicago|CST CDT|60 50|01010101010101010101010|1BQU0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0');
updateTime();
setInterval(function(){
updateTime();
},1000);
It works pretty nice, however when user changes his system clock, then the momentjs shows incorrect time. I figured out I can fetch timestamp from the server (by php) and use it as a start time for updating time on client's webpage. I tried to write a script as follows:
function updateTimeBasedOnServer(){
var timestamp = 1443618723;
var Chicago = new Date(timestamp);
var dateString = Chicago.format('h:mm:ss A');
$('#time2').html( dateString +", ");
};
updateTimeBasedOnServer();
setInterval(function(){
updateTimeBasedOnServer();
},1000);
But it doesn't work. I want to have the same result as after running the first script, but with only the difference that it works independently from the user's clock in his system. How can I do that? Here is my fiddle: http://jsfiddle.net/b8o5cvdz/9/
There is an error here:
function updateTimeBasedOnServer(){
var timestamp = 1443618723;
var Chicago = new Date(timestamp); // Here you create a Date object
var dateString = Chicago.format('h:mm:ss A'); // a Date object does not have a 'format' method. A moment.js object has it.
$('#time2').html( dateString +", ");
};
To fix it, use a moment.js object:
function updateTimeBasedOnServer() {
var timestamp = 1443618723;
var Chicago = moment(timestamp); // <- Here I create a moment.js object from the time stamp
var dateString = Chicago.format('h:mm:ss A');
$('#time2').html(dateString + ", ");
};
Here you can find a JSFiddle with the working code.
To answer you second question in the comment:
Thanks, one more thing - the 2nd date does not refresh every second - is there a way of fixing it?
You should not hard code the timestamp value (1443618723) inside the updateTimeBasedOnServer()
because at every call it will use that value. For this reason you do not see the time change.
To fix it, move the timestamp outside the method:
function updateTimeBasedOnServer(timestamp) { // Take in input the timestamp
var Chicago = moment(timestamp);
var dateString = Chicago.format('h:mm:ss A');
$('#time2').html(dateString + ", ");
};
var timestamp = 1443618723;
updateTimeBasedOnServer(timestamp);
setInterval(function () {
timestamp += 1000; // Increment the timestamp at every call.
updateTimeBasedOnServer(timestamp);
}, 1000);
Se the JSFiddle with the updated code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments