When I output a date in php or javascript, how is it calculated? Is it affected by the time a user has set on his computer or is it taken from an external source? If the user can affect it, then how do I make sure my code gets the real date/time?
2 Answers
There is a difference in technology and the context of these technologies. Meaning front-end (client side) or back-end (server side). The difference in PHP and JavaScript are on the level of invokement.
PHP
PHP is run on a dedicated server, not a clients machine. When the time function is invoked from within the PHP context, the time will be taken from the server side. Meaning the time of the hosting server.
JavaScript
JavaScript is running at client side level (browser). Time taken within the JavaScript context will take the clients operating system time. Changing your operating system time settings will have effect on your JavaScript time fetching.
In this case we are not taking into account any JavaScript back-end, like NodeJS. Since this behaves as the above mentioned PHPcontext.
Whenever I need to ensure correct Date/Time on a client side JavaScript application, I'll launch a REST request to retrieve the server time. Counting on the server time takes into account that only authenticated system admin's have control on the server Data/Time settings. And we can rely on this Date/Time truth.
Comments
Javascript gets it from the users clock
Where does javascript get a new date from
PHP gets it from the Server
PHPget the time from the server on which it's running.JavaScriptget the time from the users device as far as I know