前段時間做項目時遇到判斷目前時間是否為工作時間的需求,我認為比較有意思,所以拿出來與大家分享,一同學習。
註:
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";
}