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?
-
2Wait. 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 obtainedRaptor– Raptor2016-11-30 09:17:16 +00:00Commented Nov 30, 2016 at 9:17
-
you will need additional ajax requestYOU– YOU2016-11-30 10:29:31 +00:00Commented Nov 30, 2016 at 10:29
-
yeah.... loading may affect the accuracy of the time....with ajax post req is it possible?abhimanyu– abhimanyu2016-11-30 10:51:15 +00:00Commented Nov 30, 2016 at 10:51
-
1Bear 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.jackweirdy– jackweirdy2016-12-02 19:42:36 +00:00Commented Dec 2, 2016 at 19:42
-
'to protect this I want to use server date without any get or post request" hah, what?user400654– user4006542016-12-02 20:01:04 +00:00Commented Dec 2, 2016 at 20:01
|
Show 2 more comments
1 Answer
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:
- Use AJAX or Fetch.
- 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;
}
4 Comments
Xavier J
@epascarello it's just an AJAX call. jQuery probably does this internally with IE.
Xavier J
Believe it or not, there are still organizations where the architecture gods don't allow jQuery or any other open-source. * sigh *
Zanon
@epascarello, I've updated the answer to remove the old ActiveX reference.
Heretic Monkey
The OP specifically states "without any get or post request". You were expecting accolades for doing exactly the opposite?