html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

asp.net中时间差_.NET教程_编程技术

[ ] 已经帮助:人解决问题
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Collections;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. using System.Web.UI.WebControls.WebParts;  
  10. using System.Web.UI.HtmlControls;  
  11. using System.Data.SqlClient;  
  12.  
  13.  
  14. public partial class _Default : System.Web.UI.Page  
  15. {  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         if (!IsPostBack)  
  19.         {  
  20.             string connStr = "Server=.;Database=Test;uid=sa";  
  21.             SqlConnection conn = new SqlConnection(connStr);  
  22.             SqlCommand comm = new SqlCommand("select NowDt from Table1 where DtId = 1", conn);  
  23.             System.DateTime aa;//数据库中存的时间  
  24.             System.DateTime bb;//当前时间  
  25.  
  26.             //取数据库中时间,字段是varChar类型  
  27.             try  
  28.             {  
  29.                 conn.Open();  
  30.                 aa = Convert.ToDateTime(comm.ExecuteScalar().ToString());//数据库时间,object转为string转换为DateTime  
  31.                 conn.Close();  
  32.             }  
  33.             catch(Exception exp)  
  34.             {  
  35.                 throw exp;  
  36.             }  
  37.             finally  
  38.             {  
  39.                 conn.Dispose();  
  40.                 comm.Dispose();  
  41.             }  
  42.             this.HLOldDt.Text = aa.ToString();//输出数据库中时间  
  43.  
  44.             bb = System.DateTime.Now;//当前时间  
  45.             this.HLNowDt.Text = bb.ToString();//输出当前时间  
  46.  
  47.             //时差  
  48.             string ss = this.DateDiff(aa, bb);  
  49.             this.HLSe.Text = ss.ToString();//输出时间差  
  50.         }  
  51.     }  
  52.  
  53.     //比较时间差  
  54.     private string DateDiff(DateTime DateTime1, DateTime DateTime2)  
  55.     {  
  56.         string dateDiff = null;   
  57.           
  58.         try   
  59.         {   
  60.             TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);   
  61.             TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);   
  62.             TimeSpan ts = ts1.Subtract(ts2).Duration();//求时间差的绝对值              
  63.  
  64.             //构建时间字符串  
  65.             dateDiff = ts.Days.ToString() + " 天" + ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + " 秒";   
  66.         }  
  67.         catch  
  68.         {  
  69.         } return dateDiff;  
  70.     }  
  71. }  
  72.  
7GwHTML5中文学习网 - HTML5先行者学习网
7GwHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助