DateTime d1 =new DateTime(2004,1,1,15,36,05);
DateTime d2 =new DateTime(2004,3,1,20,16,35);
TimeSpan d3 = d2.Subtract(d1);
LbTime.Text = "相差:"
+d3.Days.ToString()+"天"
+d3.Hours.ToString()+"小时"
+d3.Minutes.ToString()+"分钟"
+d3.Seconds.ToString()+"秒";
法二、使用Sql中的DATEDIFF函数
使用方法:DATEDIFF ( datepart , startdate , enddate )
它能帮你取出你想要的各种形式的时间差,如相隔多少天,多少小时,多少分钟等,具体格式如下:

日期部分缩写

year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms



如:datediff(mi,DtOpTime,DtEnd) 便能取出他们之间时间差的分钟总数,已经帮你换算好了,对于要求规定单位,时、分、秒特别有用

追加:datediff第一个参数就是比较两个时间的哪个部分,比如年,月,天等等。参数的缩写在上面的表中。

 

我的例子:

protected void rp_GroupInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Repeater rp_Theme = (Repeater)e.Item.FindControl("rp_Theme");
                Label labgroupId = (Label)e.Item.FindControl("labgroupId");
                var pageInfo = new PageInformation
                {
                    PageSize = 6,
                    CurrentPage = ConvertHelper.ToInt32(Request.QueryString["page"], 1)
                };
                var themequery = ThemeBll.getByGroupID(System.Guid.Parse(labgroupId.Text),pageInfo);
                rp_Theme.DataSource = themequery;
                rp_Theme.DataBind();

                int icount = rp_Theme.Items.Count;
                for (int i = 0; i < icount; i++)
                {
                    Label labTime = (Label)rp_Theme.Controls[i].FindControl("labTime");
                    DateTime dtTime = Convert.ToDateTime(labTime.Text);
                    System.TimeSpan dtspanTime = DateTime.Now - dtTime;
                    if (dtspanTime.Days != 0)
                    {
                        labTime.Text = dtspanTime.Days.ToString() + "天" + dtspanTime.Hours.ToString() + "时" + dtspanTime.Minutes.ToString() + "分钟前";
                    }
                    if (dtspanTime.Days == 0 && dtspanTime.Hours != 0)
                    {
                        labTime.Text = dtspanTime.Hours.ToString() + "时" + dtspanTime.Minutes.ToString() + "分钟前";
                    }
                    if (dtspanTime.Hours == 0 && dtspanTime.Days == 0)
                    {
                        labTime.Text = dtspanTime.Minutes.ToString() + "分钟前";
                    }
                }
            }
        }