0

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
2
  • 1
    If 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. Commented Oct 3, 2013 at 16:46
  • What does H:i:s mean Hour:i:Seconds? What's up with the I. Commented Oct 3, 2013 at 16:47

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

moment.js is super awesome.
Except I'm using it with firebase to get the current time without page refresh and it's (moment.js) not working.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.