2

I have a php script that generates a date object from a database value like this:

$dt = new DateTime($string_from_database);   // In YYYY-mm-dd format
$jsonValue = $dt->format('U');

This is retrieved by my JS using AJAX. I feed it into a jQuery table like this:

            //DateStart
        {
            'sName': 'date_start',
            'iDataSort': 2,
            'bSearchable': false,
            'fnRender': function(obj) {
                var dStart = new Date(parseInt(obj.aData['DateStartJson']) * 1000);
                var dEnd = new Date(parseInt(obj.aData['DateEndJson']) * 1000);
                if (obj.aData['DateStartJson'] == obj.aData['DateEndJson'])
                    return dStart.toDateString().substr(4);
                else
                    return dStart.toDateString().substr(4) + ' -<br/>' + dEnd.toDateString().substr(4);
            }
        },

Some users are reporting that the JS time displayed is a day earlier than the date as displayed via PHP directly.

PHP displays: Aug 24, 2013 JS displays: Aug 23, 2013

Note: This happens only with some users, and I cannot reproduce it locally.

Any ideas? Jared

1 Answer 1

5

The javascript is using local machine clock, while the server is spitting out server time. Unless all of your users are in the same time zone as the server, you'll run into this issue. A solution used by many is to normalize server time to something like UTC, then make appropriate calculations on the client side javascript to account for the delta.

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

3 Comments

momentjs.com/timezone and github.com/mde/timezone-js are two actively maintained timezone libraries. [since you beat me to answering]
Thank you! Appreciate the help. Here is the function I wrote that seems to be working so far. Hard to tell since I am having difficulty reproducing the issue locally, but it is working for Mountain Time!
dateFromUnixTime : function(unixTime) { var unixTimeMs = parseInt(unixTime) * 1000; var dte = new Date(unixTimeMs); var tzo = dte.getTimezoneOffset(); // offset between user tz and utc var easternOffset = 600; // offset for east coast (server) tz var diff = (tzo - easternOffset) * 60000; // diff between the two in milliseconds return new Date(unixTimeMs - diff); },

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.