Last active
July 30, 2019 14:51
-
-
Save adactio/09015c6589afd5d911c07b9c8c7980d4 to your computer and use it in GitHub Desktop.
Compare server and client timestamps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generate a timestamp (in seconds) on the server. This won't change if the page is served from a cache. | |
var serverTimestamp = <?php echo time(); ?>; | |
// Create a new Date object from the local date and time on the client. | |
var localDate = new Date(); | |
// Convert the local date and time to Universal Time (same as the server). | |
var localUTCString = localDate.toUTCString(); | |
// Create a new Date object from the UTC date and time on the client. | |
var UTCDate = new Date(localUTCString); | |
// Generate a timestamp (in seconds) from the UTC date and time on the client. | |
var clientTimestamp = UTCDate.getTime() / 1000; | |
// Compare the server-generated timestamp to the client-generated timestamp. | |
if (clientTimestamp - serverTimestamp > (60 * 5)) { | |
document.querySelector('main').insertAdjacentHTML('afterbegin',` | |
<p class="feedback"> | |
<button onclick="this.parentNode.remove()">dismiss</button> | |
This page might be out of date. You can try <a href="javascript:window.location=window.location.href">refreshing</a>. | |
</p> | |
`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This goes in a
script
element at the bottom of a PHP page.