我知道這個問題已被問了很多次,但我有一個小的轉折。 有許多不同班次的工作,我有兩個字符串shiftStart和shiftEnd。 (例如「6:00:00 PM」&「03:00:00 AM」)。這代表中午至中午。 我想做一個函數告訴我DateTime.Now是否在這個時間週期內。當前時間在範圍內
注:移位可以是任何東西 ...早晨至中午,中午到凌晨,沒有固定的時間(如8小時)。
static bool NowWithinShiftTime("6:00:00 PM", "03:00:00 AM")
以下是我所嘗試,但無論我做什麼,我似乎無法找到邏輯... 請幫我...
static bool NowWithinShiftTime(string shiftStart, string shiftEnd)
{
DateTime startDate;
DateTime endDate;
DateTime now = DateTime.Now;
TimeSpan startTime = DateTime.Parse(shiftStart).TimeOfDay;
TimeSpan endTime = DateTime.Parse(shiftEnd).TimeOfDay;
if (startTime < endTime) // same day
{
startDate = new DateTime(now.Year, now.Month, now.Day) + startTime;
endDate = new DateTime(now.Year, now.Month, now.Day) + endTime;
}
else // next day
{
startDate = new DateTime(now.Year, now.Month, now.AddDays(-1).Hour) + startTime;
endDate = DateTime.Today.AddDays(1) + endTime;
}
if (now >= startDate && now <= endDate)
{
return true;
}
else
{
return false;
}
}
'now.AddDays(1)·小時'< - 什麼?你爲什麼要這樣做? – Katniss
@ 666bytes:你應該更喜歡'startDate = DateTime.Today + startTime',更短更清晰。對於明天,像往常一樣「AddDays(1)」。 – Jon