標籤:os io re c 時間 new
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