8

I am working on a small project where I am dealing with dates.

In order to get the today's date, I'm currently using the following JavaScript code:

    var today = new Date();

However, this results in the current date set on the client system, which may vary between systems, and hence the final output is different.

So in order to get the same result on all clients, I need to know the current date from the server. How can I get the server date in JavaScript?

3
  • 7
    "how to get current server date" - query the server... Commented Dec 15, 2012 at 6:09
  • JavaScript knows nothing about your server. Commented Dec 15, 2012 at 6:13
  • so elclanrs you know any other way to do it Commented Dec 15, 2012 at 6:20

3 Answers 3

16

Definitely getting server date is not possible without querying server.

So do a separate AJAX call to get the server date, or if your application already sends some ajax query, place the date in Date header in server-side, and read it in client.

Also if you entire page is served dynamically (like PHP), place server side date in html source like this:

<script>
   var serverDate = <?= time() ?>
   var dateDiff = new Date - serverDate;
</script>

Sign up to request clarification or add additional context in comments.

1 Comment

taha i am working with struts2 and javascript..
2

javascript runs on the client side, so will return the date of the client.

To get the date of the server, you would most likely want to use a server side language such as asp.net, php, etc.

Comments

1

You can send your server date/time in the web page and have the JavaScript determine the difference between that and the browser date.

Depending on your exact requirements, you might also consider using UTC date/time which, as its name implies, is universal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.