Compare server and client timestamps
This file contains 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.