tags:

views:

5363

answers:

3

Just wondering if there was a way to check the current date and time in Jquery.

+1  A: 

In JavaScript you can get the current date and time using the Date object;

var now = new Date();

This will get the local client machine time, if you want to do timezone adjustments or get the time from a server, check my answer to this question.


Edit: In response to your comment, you can retrieve your server time to the client side very easily:

time.php:

<? echo '{serverTime: new Date(' . time()*1000 .')}';?>

A simple JSON string is created, with a new Date object initialized with the current server time, this value is multiplied by 1000, because PHP handles timestamps in seconds, and JavaScript does it in milliseconds.

And on your other you can get the server time like this:

$.getJSON('time.php', function (data) {
  alert(data.serverTime);
});

Just make a getJSON request to retrieve the date from time.php, and access to the serverTime property of the returned object.

CMS
Is it possible to check the date on the server side using php and assign it to a variable and then use that variable in Jquery?
amir
Thanks for the answer,very helpfull,just wondering if there is a way to check for a certain day in the week (i.e friday)thanks
amir
In PHP give a look to the strtotime function http://is.gd/2budP... i.e.: strtotime("next Friday")
CMS
i am sorry to ask this, but I am curious.. is this what is called JSONP that you are getting from time.php, or is it just plain pure JSON?
Shrikant Sharat
@sharat87: Its a plain JSON response.
CMS
+2  A: 

Its not a god practice to get the current date and time from the client machine.

Make this check a server side one.

You can use jQuery to make an Ajax request to a page and then return the current date and time.

rahul
A: 

To clarify the answers provided so far...

  1. Obtaining the current date is not something that's necessary to use jquery for (Even if it had the ability to do so), as raw javascript provides this facility.

    var currentTimeAndDate = new Date();

  2. With very few exceptions, you should avoid obtaining the cuurent time/date from the client machine, as you have no way of knowing whether their clock is set correctly. Always get the time date from the server, to provide some level of predictability. This, however, is not foolproof either, as the client could genuinly be one day ahead of, or behind, the server, so ypu'll have to decide how to handle the situation in a way that suits your application.

belugabob