skip to Main Content

I am building a simple webapp in HTML, CSS, JS, PHP and MySQL. I am struggling currently with comparing dates and times. Basically, each user has an option to "bump" their listing every 2 hours, at the top of my PHP functions file I have: date_default_timezone_set('America/Toronto');. In my servers table I have a column called "last_bump" which updates to NOW(); when users bump their listing.

Not sure if this has anything to do with it, but my PC is in UTC-3:30 Newfoundland, but when I bump a listing, it starts the countdown saying 3h 29m 59s until I can bump again, which should only be +2 hours from last_bump.

Here is my code:

my-servers.php (PHP)

$lastbump = new DateTime($row['last_bump']);
                            $nextbump = new DateTime($row['last_bump']);
                            $nextbump->add(new DateInterval('PT2H'));

                            $currenttime = new DateTime();

                            if ($currenttime >= $nextbump) {
                                echo '<a href="#" class="btn btn-primary-sm" data-server-id="' . $row['id'] . '">Bump Server</a>';
                            } else {
                                // Calculate time difference in seconds
                                $timeDiff = $nextbump->getTimestamp() - $currenttime->getTimestamp();
                                echo '<div class="countdown text-center" data-time="' . $timeDiff . '"></div>';
                            }

my-servers.php (JS)

function startCountdown(element, time) {
            let countdownTime = time;

            const updateCountdown = () => {
                if (countdownTime > 0) {
                    countdownTime--;

                    const hours = Math.floor(countdownTime / 3600);
                    const minutes = Math.floor((countdownTime % 3600) / 60);
                    const seconds = countdownTime % 60;

                    // Create a readable countdown string
                    let countdownText = 'Next Bump: ';
                    if (hours > 0) {
                        countdownText += `${hours}h `;
                    }
                    if (minutes > 0 || hours > 0) {
                        countdownText += `${minutes}m `;
                    }
                    countdownText += `${seconds}s`;

                    element.innerText = countdownText;
                } else {
                    element.innerText = 'You can bump now!';
                    clearInterval(countdownInterval);
                    location.reload(); // Refresh the page to show the bump button
                }
            };

            updateCountdown(); // Initial call to display the timer
            const countdownInterval = setInterval(updateCountdown, 1000);
        }

        // Initialize countdown for each countdown element
        document.querySelectorAll('.countdown').forEach(element => {
            const time = parseInt(element.getAttribute('data-time'), 10);
            startCountdown(element, time);
        });

api/bump-server.php

include '../functions.php'; // Adjust path as per your file structure

// Ensure POST data exists and is JSON
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

// Ensure JSON data was successfully decoded
if ($input === null) {
    http_response_code(400); // Bad request
    echo json_encode(array('error' => 'Invalid JSON data'));
    exit;
}

// Retrieve and sanitize server_id from JSON data
$server_id = isset($input['server_id']) ? intval($input['server_id']) : null;

if (!$server_id) {
    http_response_code(400); // Bad request
    echo json_encode(array('error' => 'Invalid server ID'));
    exit;
}

// Perform database update to set last_bump timestamp
$stmt = $conn->prepare("UPDATE servers SET last_bump = NOW() WHERE id = ?");
$stmt->bind_param('i', $server_id);

if ($stmt->execute()) {
    // Success response
    http_response_code(200); // OK
    echo json_encode(array('success' => true));
} else {
    // Error response
    http_response_code(500); // Internal server error
    echo json_encode(array('error' => 'Failed to update server bump'));
}

$stmt->close();

I tried adding a different column in my database table called next_bump but same issues.

Edit:

When removing "date_default_timezone_set(‘America/Toronto’);" – I can constantly bump servers, without having to wait any time…

2

Answers


  1. Chosen as BEST ANSWER

    I had totally forgotten about UTC, I had a brain freeze. What I did to fix my issue was change my timezone from date_default_timezone_set('America/Toronto') > date_default_timezone_set('UTC').


  2. Also you can forget timezone completely

    1. Create a table user_bump with 2 column: userid and last bump of that user in unix format

    2. When a user bumped, update its own row with its own unix time simply

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search