Working with server time in JavaScript (and PHP)
Dealing with timezone offsets can be frustrating in any coding environment. It’s pretty easy to get the server time into the client side JavaScript using PHP. The following code will create a JavaScript Date object that holds the current server date/time:
<script type="text/javascript">
var dateServer = new Date('<?= date('F d, Y H:i:s') ?>');
<script type="text/javascript">
Once that’s done you can work with the dateServer Date object and it will reflect the server’s local date/time. However, what if I need to calculate the date multiple times on-the-fly (e.g. - from within in a loop)? That might come in handy for things like timer scripts. We’ll first need to know the offset between the server time and local time:
<script type="text/javascript">
var dateLocal = new Date();
var dateServer = new Date('<?= date('F d, Y H:i:s') ?>');
var dateOffset = dateServer - dateLocal;
<script type="text/javascript">
dateOffset now holds the offset in milliseconds. Here’s how to make use of the offset for future JavaScript Date object instances:
<script type="text/javascript">
var dateLocal = new Date();
var dateServer = new Date('<?= date('F d, Y H:i:s') ?>');
var dateOffset = dateServer - dateLocal;
var newDate = new Date();
newDate.setTime(newDate.getTime() + dateOffset);
<script type="text/javascript">
That’s it! The newDate variable now holds the server time using the calculated offset from the previous PHP date() call.
UPDATE: I have created an example script that illustrates its use in a recursive clock function. As a side note, the setTimeout() JavaScript function produced much better results than setInterval() for this particular application. setInterval() was causing it to skip seconds for some reason, possibly something to do with this computer being bogged down with processes. At any rate, while setInterval() looks cleaner and more elegant, it looks like setTimeout() is the ideal route for a live timer or clock script.