karthi k
karthi k

Reputation: 51

Countdown timer showing wrong for the given date and time

I am creating a simple countdown timer which takes difference from two dates and outputs it like: 01 day 23 hours 59 minutes

In PHP:

$this_is_old_date = 2020-06-08 13:52:18; // let's take it as tody date
$old_date = DateTime::createFromFormat('Y-m-d H:i:s', $this_is_old_date);
$expire = clone $old_date;
$expire->add(new DateInterval('P2D')); // add two days from today date
$exp = $expire->format('Y-m-d H:i:s');

Everything works fine

In javascript:

function getTimeRemaining(expire) {
    var t = Date.parse(expire) - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
}

var expire = "<?php echo $exp; ?>";
getTimeRemaining(expire);

When I call this function getTimeRemaining(expire) it start with 1 day 20 hours 30 minutes, But my expected time is 01 day 23 hours 59 minutes how to fix it?

Thanks in advance :)

Upvotes: 4

Views: 490

Answers (1)

Tibebes. M
Tibebes. M

Reputation: 7548

Try making all dates to the same timezone (to resolve the difference error as @cyborg86pl mentioned in the comments)

Do something like this.

PHP:


date_default_timezone_set('UTC')

$this_is_old_date = 2020-06-08 13:52:18; // let's take it as tody date
$old_date = DateTime::createFromFormat('Y-m-d H:i:s', $this_is_old_date);
$expire = clone $old_date;
$expire->add(new DateInterval('P2D')); // add two days from today date
$exp = $expire->format('Y-m-d H:i:s');

JavaScript:

function utcDate(date) {
    return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()));
}

function getTimeRemaining(expire) {
    var t = utcDate(new Date(Date.parse(expire))) - utcDate(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
}

var expire = "<?php echo $exp; ?>";
getTimeRemaining(expire);

Upvotes: 1

Related Questions