Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Server date in JavaScript [closed]

Tags:

javascript

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?

like image 387
Aniket Avatar asked Dec 15 '12 06:12

Aniket


People also ask

How to get server date in JavaScript?

JavaScript Methodvar datetime=getservertime(false,""); The following commands can be used to obtain various constituent portions of the server date and time: datetime. getfieldbyname(1,"servertime") --> returns the server time in YYYY-MM-DD HH:MM:SS.

What is new Date () in JavaScript?

It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


1 Answers

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>

like image 78
Taha Jahangir Avatar answered Sep 21 '22 06:09

Taha Jahangir