In JavaScript, you cannot change the server time directly, because JavaScript is a client-side language and does not have direct access to server settings. However, you can use the following methods to synchronize or change the time for your website to stay with us until the end of this article from Radib:


1. Get the server time via API and display it on the website

To ensure that the server and client time are synchronized, you can get and display the server time via AJAX or Fetch API.

Example:

<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Server Time</title>
</head>
<body>

<h2>Server Time: <span id="serverTime"></span></h2>

<script>
async function fetchServerTime() {
try {
let response = await fetch('/get-server-time');
let data = await response.json();
document.getElementById('serverTime').innerText = data.time;
} catch (error) {
console.error('Error getting time:', error);
}
}

setInterval(fetchServerTime, 1000); // Update every second
fetchServerTime();
</script>

</body>
</html>
HTML

Note: This code requires a Server API that sends the current time in JSON format.

Buy high-speed cPanel and DirectAdmin hosting from Radib, with instant delivery, Click


2. Simulating time changes in the client browser

If you want to artificially change the time (for example, to display a custom time zone), you can use the following method:

Example:

<script>
function adjustClientTime(offsetHours) {
let currentDate = new Date();
currentDate.setHours(currentDate.getHours() + offsetHours);
document.getElementById('clientTime').innerText = currentDate.toLocaleString();
}

setInterval(() => adjustClientTime(3), 1000); // 3 hour change
</script>

<h2>Time set: <span id="clientTime"></span></h2>
HTML

3. Using timing libraries like Moment.js

Libraries like Moment.js and date-fns can help you manage and change time.

Buy a cloud clock server or get instant delivery from Radib, Click

Install Moment.js via CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
let time = moment().utcOffset(330).format('YYYY-MM-DD HH:mm:ss');
document.write("Time set: " + time);
</script>
HTML

4. Setting the timezone on the server and sending it to the client

If your server uses PHP, Node.js or Python, you can change the timezone on the server and send it to the client.

Example in PHP:

<?php
date_default_timezone_set("Asia/Tehran");
echo json_encode(["time" => date("Y-m-d H:i:s")]);
?>
PHP

Then get it and display it in JavaScript.


Conclusion

  • To actually change the server time, you should use backend languages ​​like PHP, Node.js.
  • If the goal is just to display time changes, you can use JavaScript-based methods like Date or related libraries.

If you need further assistance, please contact us in tickets. Radib experts are available 24/7.

Was this answer helpful? 95 Users Found This Useful (95 Votes)