DateTime.Compare(t1,t2)比较两个日期大小,排前面的小,排在后面的大,比如:2011-2-1就小于2012-3-2
返回值小于零: t1 小于 t2。
返回值等于零 : t1 等于 t2。
返回值大于零: t1 大于 t2。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DateTime t1 = DateTime.Parse("2011-2-2"); DateTime t2 = DateTime.Parse("2011-3-1"); if (DateTime.Compare(t1, t2) > 0) Console.WriteLine("t1 > t2"); if (DateTime.Compare(t1, t2) == 0) Console.WriteLine("t1 == t2"); if (DateTime.Compare(t1, t2) < 0) Console.WriteLine("t1 < t2"); } } }
运行结果:
t1 < t2
请按任意键继续. . .
例
以下逻辑表示:
每天2人轮流值班,每天08:30进行一次换班,每天17:30进行一次换班,当天08:30之前的调用上一天第二人值班
/// <summary> /// 时间比较,与当前系统时间比较,若返回1,表示t1小;若返回-1,表示t1大 /// </summary> /// <param name="t1"></param> /// <returns></returns> private static int CompareTime(string t1) { int str = 0; if (DateTime.Compare(Convert.ToDateTime(t1), Convert.ToDateTime(DateTime.Now.ToString("HH:mm:ss"))) >= 0) { str = 1; } else { str = -1; } return str; }
string morning_time = "08:30:00"; string night_time = "17:30:00";
if (CompareTime("00:00:00") == -1 && CompareTime(morning_time) == 1)//处于当日00:00-08:30之间,选择上一天第二人 { strWhere = " work_date='" + (DateTime.Now.Day - 1).ToString() + "'"; } else if (CompareTime(morning_time) == -1 && CompareTime("23:59:59") == 1)//处于当日08:30:00-23:59:59之间,选择当天第一人或第二人 { strWhere = " work_date='" + DateTime.Now.Day.ToString() + "'"; }
string[] StrWordList = StrWord.Split('|'); StrWordList = strTo(StrWordList);//去除数组中重复和空白的元素 if (StrWord.Length >= 2 && StrNumList.Length >= 2) { returnStr = ""; if (type == "top") { if (CompareTime("00:00:00") == -1 && CompareTime(morning_time) == 1)//处于当日00:00-08:30之间,选择上一天第二人 { returnStr = "<a href="manager/work.aspx" target="mainframe">" + StrWordList[1].ToString() + StrNumList[1] + "</a>"; } else if (CompareTime(morning_time) == -1 && CompareTime(night_time) == 1)//处于当日08:00-17:30之间,选择当天第一人 { returnStr = "<a href="manager/work.aspx" target="mainframe">" + StrWordList[0].ToString() + StrNumList[0] + "</a>"; } else if (CompareTime(night_time) == -1 && CompareTime("23:59:59") == 1)//处于当日17:30-24:00之间,选择当天第二人 { returnStr = "<a href="manager/work.aspx" target="mainframe">" + StrWordList[1].ToString() + StrNumList[1] + "</a>"; } }
}