Answered
How to read Internet time with JS?
Hi everyone.
I want to check the system time when running the script every Monday.
Thank you.
Hi everyone.
I want to check the system time when running the script every Monday.
Thank you.
I just want to read the Internet date,
then compare it with the local date. Only when the two are the same will the script be able to run.
Do you think this will suit you? It grabs the timestamp from a HTTP request. Not an Internet time server, but might be a reasonable proxy.
(function () {
// Usage:
try {
var nowAccordingToGoogle = getInternetTimeViaHTTP();
var nowAccordingToComputer = new Date();
alert('Times:'
+ '\nUTC time from google.com is:\n' + nowAccordingToGoogle.toUTCString()
+ '\nUTC time from your computer is:\n' + nowAccordingToComputer.toUTCString()
);
} catch (e) {
alert("Error: " + e);
}
})();
/**
* Returns the time according to response of HTTP request to google.com.
* @7111211 ChatGPT and m1b
* @version 2025-08-06
* @Returns {Date}
*/
function getInternetTimeViaHTTP() {
var socket = new Socket();
if (!socket.open("google.com:80", "UTF-8"))
throw new Error("Could not open socket");
// Send a minimal HEAD request
socket.write("HEAD / HTTP/1.0\r\nHost: google.com\r\n\r\n");
// Read entire response
var resp = "";
while (!socket.eof)
resp += socket.read(1024);
socket.close();
// Find the Date: header
var m = resp.match(/^Date:\s*(.+)$/mi);
if (!m)
throw new Error("No Date header in response");
// Parse (e.g. "Tue, 06 Aug 2024 12:34:56 GMT")
var dateStr = m[1];
return new Date(dateStr);
};
Already have an account? Login
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.