β

C#计算时间差。

程序人生 575 阅读

C#中怎么计算两时间相差多少。计算2个时间之间的差,可以计算到时分秒!

<1>
label1.Text = “2004-1-1 15:36:05″;
label2.Text = “2004-3-1 20:16:35″;
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);

label3.Text = “相差:”
+d3.Days.ToString()+”天”
+d3.Hours.ToString()+”小时”
+d3.Minutes.ToString()+”分钟”
+d3.Seconds.ToString()+”秒”;


<2>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime dt1 = Convert.ToDateTime(“2009-07-31 00:00:00″);
DateTime dt2 = Convert.ToDateTime(“2009-08-02 00:00:00″);
this.Label1.Text = this.DateDiff(dt1,dt2);
}
}
private string DateDiff(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
try
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + “天” + ts.Hours.ToString() + “小时” + ts.Minutes.ToString() + “分钟” + ts.Seconds.ToString() + “秒”;
}
catch
{ }
return dateDiff;
}

<3>
string st1 = “14:16″;
string st2 = “14:14″;
DateTime dt1 = Convert.ToDateTime(st1);
DateTime dt2 = Convert.ToDateTime(st2);

int result = DateTime.Compare(dt1, dt2);
如果st1的时间大于st2  , result = 1
如果相等就等于0,
如果小于就是-1

作者:程序人生
关注移动互联网和编程专业技术的IT科技博客
原文地址:C#计算时间差。, 感谢原作者分享。