I'm using this javascript code to sync the client time with my server time
var offset = 0;
function calcOffset() {
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("GET", "http://stackoverflow.com/", false);
xmlhttp.send();
var dateStr = xmlhttp.getResponseHeader('Date');
var serverTimeMillisGMT = Date.parse(new Date(Date.parse(dateStr)).toUTCString());
var localMillisUTC = Date.parse(new Date().toUTCString());
offset = serverTimeMillisGMT - localMillisUTC;
}
function getServerTime() {
var date = new Date();
date.setTime(date.getTime() + offset);
return date;
}
the date I get back is
"2013-10-03T16:37:05.568Z"
How to I make this "2013-10-03 H:i:s"?
Dennis Meng
5,16214 gold badges35 silver badges37 bronze badges
asked Oct 3, 2013 at 16:43
user2320607
4251 gold badge9 silver badges19 bronze badges
-
1If you are working with dates, momentjs.com is a great resource. Javscript's native handling for dates isn't very clean or smooth. That being said, there is an answer to this in vanilla JS which I'll put up if I can get it there before anyone else, hah.Jeff Escalante– Jeff Escalante2013年10月03日 16:46:14 +00:00Commented Oct 3, 2013 at 16:46
-
What does H:i:s mean Hour:i:Seconds? What's up with the I.0xcaff– 0xcaff2013年10月03日 16:47:56 +00:00Commented Oct 3, 2013 at 16:47
1 Answer 1
Although using moment.js is a smoother way to do it if you are working with a bunch of dates, here's a way to do it with vanilla JS:
x = new Date
x.getFullYear() + '-' + x.getMonth() + '-' + x.getDay()
Edit:
Here it is with the time and leading zeros on the month and day, as you can see these extra things add a good bit more code. Maybe if you post another question detailing your troubles with moment.js, we would be able to help getting it fixed:
formatDate(new Date);
function formatDate(d){
var year = d.getFullYear();
var month = addLeadingZero(d.getMonth());
var day = addLeadingZero(d.getDay());
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
function addLeadingZero(n){ return n < 10 ? '0'+n : ''+n }
answered Oct 3, 2013 at 16:49
Jeff Escalante
3,1671 gold badge23 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
JAAulde
moment.js is super awesome.
user2320607
Except I'm using it with firebase to get the current time without page refresh and it's (moment.js) not working.
lang-js