asp.net+javascript倒计时
经常我们会使用商品秒杀倒计时等时间计算功能,很多时候直接使用客户端时间计算,如果客户端时间不准,给客户带来一些困扰。
为此重新写了一个倒计时模块,顺便做个备案。
功能实现思路:
1、后端代码得到服务器当前时间与到期时间,然后计算出时间差秒数,传递到前台。
2、前端计算出天数、小时、分钟、秒,然后显示到前台,并每秒自动更新一次。
后端代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.UI; 5 using System.Web.UI.WebControls; 6 7 public partial class _Default : System.Web.UI.Page 8 { 9 public int timeStamp = 0; 10 protected void Page_Load(object sender, EventArgs e) 11 { 12 13 DateTime nowTime = DateTime.Now; 14 DateTime endTime = new DateTime(2013, 4, 5, 12, 45, 23); 15 16 TimeSpan ts1 = new TimeSpan(nowTime.Ticks); 17 TimeSpan ts2 = new TimeSpan(endTime.Ticks); 18 double ts = ts2.Subtract(ts1).TotalSeconds; 19 timeStamp = Convert.ToInt32(ts); 20 } 21 }
前端代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title></title> 8 </head> 9 <body> 10 <form id="form1" runat="server"> 11 <div id="time"> 12 13 </div> 14 </form> 15 <script type="text/javascript"> 16 (function () { 17 var diffDate = < %= timeStamp % > ; 18 var _time = null; 19 20 function refTime() { 21 if (diffDate <= 0) { 22 document.getElementById("time").innerHTML = "已经过期"; 23 if (_time != null) { 24 clearInterval(_time); 25 } 26 return; 27 } 28 var days = Math.floor(diffDate / (24 * 3600)); 29 var leave1 = diffDate % (24 * 3600); 30 var hours = Math.floor(leave1 / (3600)); 31 var leave2 = leave1 % (3600); 32 var minutes = Math.floor(leave2 / (60)); 33 var leave3 = leave2 % (60); 34 var seconds = Math.round(leave3); 35 var _html = ""; 36 if (days > 0) { 37 _html += days + "天"; 38 } 39 if (hours > 0) { 40 _html += hours + "时"; 41 } 42 if (minutes > 0) { 43 _html += minutes + "分"; 44 } 45 _html += seconds + "秒"; 46 document.getElementById("time").innerHTML = _html; 47 diffDate--; 48 } 49 _time = setInterval(function () { 50 refTime() 51 }, 1000); 52 refTime(); 53 })(); 54 55 </script> 56 </body> 57 </html>