3

I am using AngularJS client-side application and working with date and time. My problem is that local system date anyone can change, to protect this I want to use server date without any get or post request. Is there any way to get server date using JavaScript?

7
  • 2
    Wait. JavaScript is client-side language. You will need to "ask" server-side to fetch its time. Note that connection & loading time may affect the accuracy of time obtained Commented Nov 30, 2016 at 9:17
  • you will need additional ajax request Commented Nov 30, 2016 at 10:29
  • yeah.... loading may affect the accuracy of the time....with ajax post req is it possible? Commented Nov 30, 2016 at 10:51
  • 1
    Bear in mind that even if you successfully get the date from the server, a malicious client could still change it. If an accurate date is system-critical you will have to validate on the server side. Commented Dec 2, 2016 at 19:42
  • 'to protect this I want to use server date without any get or post request" hah, what? Commented Dec 2, 2016 at 20:01

1 Answer 1

5

If you are running JavaScript at the client-side, the only way to find the server time is asking the server what is the current time. There is no magic here. You need to make a request to the server.

Options:

  1. Use AJAX or Fetch.
  2. If the HTML page is rendered in the server, you can write the current time during the page render and send it to client.

Please, note that it is not possible to have a precise time of the server due to network delays, but you can get pretty close using the code from this answer (modified):

var offset = 0;
function calcOffset() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "https://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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

@epascarello it's just an AJAX call. jQuery probably does this internally with IE.
Believe it or not, there are still organizations where the architecture gods don't allow jQuery or any other open-source. * sigh *
@epascarello, I've updated the answer to remove the old ActiveX reference.
The OP specifically states "without any get or post request". You were expecting accolades for doing exactly the opposite?

Your Answer

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.