asp.net中的倒计时器

时间:2010-05-20 07:22:45

标签: c# asp.net countdown

我正在使用带有C#的asp.net 3.5。 我想创建一个倒数计时器,我的要求是这样的:

倒计时结束日期:2010年6月16日 因此,直到6月16日,我的计时器将显示重新计算的时间。

请让我知道如何实现它,我谷歌它但我没有得到我的问题的解决方案。

提前致谢。

2 个答案:

答案 0 :(得分:5)

这是您需要使用Javascript解决的问题。您需要从服务器执行的唯一操作是将结束日期设置为Javascript变量。您需要Javascript,因为您只从服务器加载页面。之后你需要处理客户端的倒计时。

<强>的Javascript

<script type="text/javascript">
    function countdown_clock(clockID, year, month, day, hour, minute) {
        countdown(clockID, year, month, day, hour, minute);
    }

    function countdown(clockID, year, month, day, hour, minute) {
        Today = new Date();
        Todays_Year = Today.getFullYear();
        Todays_Month = Today.getMonth();

        //Convert both today's date and the target date into miliseconds.                           
        Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
                             Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
        Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();

        //Find their difference, and convert that into seconds.                  
        Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

        if (Time_Left < 0)
            Time_Left = 0;

        days = Math.floor(Time_Left / (60 * 60 * 24));
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        Time_Left %= 60;
        seconds = Time_Left;

        dps = 's'; hps = 's'; mps = 's'; sps = 's';
        //ps is short for plural suffix.
        if (days == 1) dps = '';
        if (hours == 1) hps = '';
        if (minutes == 1) mps = '';
        if (seconds == 1) sps = '';

        var clock = document.getElementById(clockID);
        clock.innerHTML = days + ' day' + dps + ' ';
        clock.innerHTML += hours + ' hour' + hps + ' ';
        clock.innerHTML += minutes + ' minute' + mps + ' and ';
        clock.innerHTML += seconds + ' second' + sps;

        //Recursive call, keeps the clock ticking.
        setTimeout('countdown("' + clockID + '",' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ');', 1000);
    }
</script>

<强> ASP.NET

protected override void OnPreRender(EventArgs e)
    {
        DateTime endDate = new DateTime(2010, 6, 1, 0, 0, 0);
        string script = string.Format("countdown_clock('clock', {0}, {1}, {2}, {3}, {4});", endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute);
        ScriptManager.RegisterStartupScript(this, this.GetType(), "countdown", script, true);

        base.OnPreRender(e);
    }

脚本采用My Little Scripts为例进行修改。

答案 1 :(得分:0)

如果您喜欢它,请使用DateTime。

DateTime EventTime = new DateTime(2010, 6, 16);
TimeSpan Duration = EventTime - DateTime.Now;
string TimeTillEvent = Duration.ToString();