前段时间做项目时遇到判断当前时间是否为工作时间的需求,我认为比较有意思,所以拿出来与大家分享,一同学习。
注:
1._strWorkingDayAM等值,这里赋默认值,通常情况下应读配置文件。
2.clsArrayList类是将字符串截取为数组的功能类,在我的博客中有写,有兴趣的朋友可以看一下。
private string _strWorkingDayAM="08:00";//工作时间上午08:00
private string _strWorkingDayPM = "16:00";
private string _strRestDay="6,7";//周几休息日 周六周日为 6,7
private TimeSpan dspWorkingDayAM;//工作时间上午08:00
private TimeSpan dspWorkingDayPM;
clsArrayList myArrayList;
private bool m_IsWorkingDay()
{
string strWeekNow = this.m_GetWeekNow();//当前周几
//判断是否有休息日
for (int i = 0; i < myArrayList.p_Count; i++)
{
if (strWeekNow == myArrayList.m_GetItem(i))
{
return false;
}
}
//判断当前时间是否在工作时间段内
TimeSpan dspNow = DateTime.Now.TimeOfDay;
if (dspNow > dspWorkingDayAM && dspNow < dspWorkingDayPM)
{
return true;
}
return false;
}
//初始化默认值
private void m_InitWorkingDay()
{
dspWorkingDayAM = DateTime.Parse(_strWorkingDayAM).TimeOfDay;
dspWorkingDayPM = DateTime.Parse(_strWorkingDayPM).TimeOfDay;
myArrayList = new myClass.clsArrayList(_strRestDay, ',');
}
//调用
void Button1Click(object sender, EventArgs e)
{
this.m_InitWorkingDay();
bool bol = this.m_IsWorkingDay();
MessageBox.Show(bol.ToString());
}//获取当前周几
private string m_GetWeekNow()
{
string strWeek = DateTime.Now.DayOfWeek.ToString();
switch (strWeek)
{
case "Monday" :
return "1";
case "Tuesday":
return "2";
case "Wednesday":
return "3";
case "Thursday":
return "4";
case "Friday":
return "5";
case "Saturday":
return "6";
case "Sunday":
return "7";
}
return "0";
}