我正在使用asp.net 3.5與C#。 我想創建一個倒數計時器,我的要求是這樣的:asp.net中的倒數計時器
倒計時結束日期:2010年6月16日 因此,直到6月16日來我的計時器將顯示remeaning時間。
請讓我知道如何實現它,我谷歌它,但我沒有得到解決我的問題的激動人心的解決方案。
在此先感謝。
我正在使用asp.net 3.5與C#。 我想創建一個倒數計時器,我的要求是這樣的:asp.net中的倒數計時器
倒計時結束日期:2010年6月16日 因此,直到6月16日來我的計時器將顯示remeaning時間。
請讓我知道如何實現它,我谷歌它,但我沒有得到解決我的問題的激動人心的解決方案。
在此先感謝。
這是你需要用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。
完美!謝謝 :) – Zerotoinfinity 2010-05-22 20:51:07
如果您喜歡,請使用DateTime。
DateTime EventTime = new DateTime(2010, 6, 16);
TimeSpan Duration = EventTime - DateTime.Now;
string TimeTillEvent = Duration.ToString();
Hi Marks, 感謝您的回覆。 如何讓數字時鐘每秒鐘的時間縮短? – Zerotoinfinity 2010-05-20 07:33:11
如果你想讓它倒數生活,你無法繞過使用javascript。看看Joop的回答。我的解決方案僅適用於每個reuquest的更新。 – Marks 2010-05-20 16:08:42
此外,我想顯示定時器每秒減少。 請幫忙 – Zerotoinfinity 2010-05-20 07:28:28