javascript 和 php 中的时间戳倒计时

问题描述 投票:0回答:2

我需要一些帮助来编写一个脚本,从 UNIX 时间戳开始倒计时天、小时、分钟和秒。

时间戳是用php创建的

<? php echo hours ();?>

我希望脚本能够使用 JavaScript 实时倒计时。

示例 2 天,3:15:39

希望有人能帮助我一点:)

php javascript jquery
2个回答
10
投票

首先你会遇到一些 PHP 错误。应该是例如

<?php echo time(); ?>

我在 JavaScript 中使用时间戳以便于展示示例。

http://jsfiddle.net/pimvdb/AvXd3/

// the difference timestamp
var timestamp = (Date.now() + 1000 * 60 * 60 * 24 * 3) - Date.now();

timestamp /= 1000; // from ms to seconds

function component(x, v) {
    return Math.floor(x / v);
}

var $div = $('div');

setInterval(function() { // execute code each second

    timestamp--; // decrement timestamp with one second each second

    var days    = component(timestamp, 24 * 60 * 60),      // calculate days from timestamp
        hours   = component(timestamp,      60 * 60) % 24, // hours
        minutes = component(timestamp,           60) % 60, // minutes
        seconds = component(timestamp,            1) % 60; // seconds

    $div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); // display

}, 1000); // interval each second = 1000 ms

0
投票

我刚刚重构了上面的代码

var limitDays = 1000 * 60 * 60 * 24 //"24 hours"
var days = 365
var expired = false

var currentTime = new Date()
console.log("set var [ now ] with this: ", currentTime.valueOf())
console.log("set var [ validity ] with this: ", getTime())

function getTime() {
    return days * limitDays
}

function component(x, v) {
    return Math.floor(x / v);
}

function getTimer(timestamp) {
    var interval = setInterval(function() {
        timestamp -= 1000
        var days = component(timestamp / 1000, 24 * 60 * 60),
            hours = component(timestamp / 1000, 60 * 60) % 24,
            minutes = component(timestamp / 1000, 60) % 60,
            seconds = component(timestamp / 1000, 1) % 60;

        document.getElementById('countdown').innerHTML = (days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds")

        if (timestamp < 0) {
            console.log("expired")
            clearInterval(interval)
            getTimer(getTime())
        }
    }, 1000)
}

var validity = 31536000000
var now = 1711578707493
var converter = (validity - (currentTime.valueOf() - now))
getTimer(converter)
<!DOCTYPE html>
<html>
 <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    </head>
    <body> 
    <div id="countdown"></div>  
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.