Get server date time in Javascript

Hi
I have been trying to find a way of getting the server date time [localhost] in javascript. From my understanding this only can be done via AJAX. I have found a code that does the job but currently it outputs the date to a input box, I need it to return the date/time into a variable.

function ashserverdate() {
  $.ajax({
    type: 'GET',
    cache: false,
    url: location.href,
    complete: function (req, textStatus) {
      var dateString = req.getResponseHeader('Date');
      if (dateString.indexOf('GMT') === -1) {
        dateString += ' GMT';
      }
      var date = new Date(dateString);
      $('.ssDateTime').val(date.toString());
    }
  });
}

Open in new window

LVL 1
ACEAFTYAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
It is all in the code already - see comments below.
function ashserverdate() {
  $.ajax({
    type: 'GET',
    cache: false,
    url: location.href,
    complete: function (req, textStatus) {
      // HERE IS THE STRING VERSION OF THE DATE
      var dateString = req.getResponseHeader('Date');
      if (dateString.indexOf('GMT') === -1) {
        dateString += ' GMT';
      }
      // HERE IS THE JAVASCRIPT VERSION OF THE DATE
      var date = new Date(dateString);
      $('.ssDateTime').val(date.toString());
    }
  });
}

Open in new window

ACEAFTYAuthor Commented:
Currently when I want to execute the above function I add the following line of code:

ashserverdate();

But I want to be add a return to the function so I can do the following:

var newdate = ashserverdate();

So I can use newdate variable later else where in the code.
Julian HansenCommented:
AJAX - the a stands for asynchronous. There is an option to set async: false which will block the AJAX call until it has completed but this is not advisable as it blocks all events on the page.

You should be using the callbacks to do what you want to do.

What do you want to do with newdate - lets look at it from that perspective?

I would do something like this
var newdate = false;
$(function() {
  // first call you make is to get the date
  $.ajax({
   ...
    complete: function (req, textStatus) {
      var dateString = req.getResponseHeader('Date');
      if (dateString.indexOf('GMT') === -1) {
        dateString += ' GMT';
      }
      var newdate = new Date(dateString);
    }
});
...
// Code here access newdate which will be false until the above completes 

Open in new window


What I would do is to initialize the newdate value with a value from server side script
PHP
<?php echo "var newdate='" . Date('Y-m-d H:i:s') ."'";?>

Open in new window

That way the value starts out with a value and if you need to update it - it will still have a valid value until the AJAX call overwrites it.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Julian HansenCommented:
Here is another option. Your onload calls a config function and then terminates. The config function makes the AJAX call and in the success / done / always callback it calls the run() function which is where your code runs. This way the run() function does not run until the callback to the server is complete.
<script>
var newdate = false;
function config()
{
  $.ajax({
    url: '/'
  })
  .always(function(resp, status, xhdr) {
    var dateString = xhdr.getResponseHeader('Date');
    newdate = new Date(dateString);
    run();
  });
}

$(function() {
  config();
});

function run()
{
  alert('rest of code here: ' + newdate)
}
</script>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ACEAFTYAuthor Commented:
I have tried both solutions and not having much luck, your 2nd option works but the newdate only works in the run function, if I try using it in another function it doesn't work. Also it is limited only to 1 variable newdate.

What I'm trying to achieve is, I have a jsFlipClock script, I need the server datetime to initialise the countdown and when the timer reaches 0 at 3pm, the 24 hour countdown starts again. I need to call the function that gets the server datetime and returns the datetime to variable at any point in the script.

var initialiseDate = ashserverdate();

and may be later in the script: var currentdate = ashserverdate();

In these AJAX complete functions is there a way of inserting a 'return' command that passes the date back out, like in a standard javascript function.

Hope you understand what I'm trying to get done. I'm completely new to AJAX and I don't have enough understanding of it to play around with the code myself.
Julian HansenCommented:
but the newdate only works in the run function
The run function is where you need to put all your code. In other words any other function would need to be called from run - think of it as your onload i..e run will only execute after newdate has been set - you then put all the rest of your code in run.

In these AJAX complete functions is there a way of inserting a 'return' command that passes the date back out, like in a standard javascript function.
That's not how it works - AJAX is asynchronous - so the call is made and execution continues while the call completes in the background - this can take a variable amount of time.

When writing these applications you need to structure your logic around the call back so that whatever needs to happen when it completes is initiated from the callback.

In your case you should consider using the global variable newdate as described in my earlier post. This initialises the date on startup - you can then use setInterval to make AJAX calls in the background to update that time at regular intervals - but at all times your code uses newdate - and not a return value from a function - your application makes the assumption that newdate will have a relevant value and the background processes ensure that the newdate value is kept up to date.
ACEAFTYAuthor Commented:
Thanks for the help. I didn't know how AJAX worked and didn't realise there can be a delay in update the value in the variable. I have managed to implement this solution.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.