1. 比較時間前後 使用 DateTime.Compare
// 參考來源 http://goo.gl/Ay5hAE
using System;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
}
}
// The example displays the following output:
// 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
2. 比較時間差異 使用 SQL語法
// http://goo.gl/nTQX3D 每日一SQL-善用DATEADD和DATEDIFF // http://goo.gl/PrB0JC 如何用簡單的 SQL 技巧取得特定日期是否為週末假日 SELECT DATEDIFF(DAY, '2010-10-03','2010-10-04' ) // 出來的結果就是 1,代表相隔一天。
2. 比較時間差異 使用 TimeSpan
DateTime ts1 = Convert.ToDateTime(sqlDDT.Rows[0][1].ToString()); // 取得datatable欄位資料並轉時間格式
DateTime ts2 = DateTime.Now; // 抓取現在時間
Double ts = new TimeSpan(ts2.Ticks - ts1.Ticks).TotalSeconds;
if (ts >= 60)// 判斷時間差異 時間差大於60秒 則執行
{
// do
}
// 關於 TimeSpan 的屬性使用可以參考
// http://goo.gl/NqvtYy
// Hours 與 TotalHours 是有差別的(前者是只有比較Hours後者則是算整個的時間差-會包含日的換算)

沒有留言:
張貼留言