你可以嘗試這樣的事情,使用功能「IsTimeOfDayBetween」你已經有:
// global variables
TimeSpan dayStart = new TimeSpan(0, 0, 0);
TimeSpan dayEnds = new TimeSpan(23, 59, 59);
// you have a timer(loop) every sencond, so you can have this two variables change depending on what market you are tracking, in this example NY
TimeSpan NyOpens = new TimeSpan(8, 0, 0);
TimeSpan NyClose = new TimeSpan(16, 0, 0);
// variable to store the result
TimeSpan tillOpenClose;
if ((IsTimeOfDayBetween(DateTime.UtcNow, NyOpens, NyClose)) == true)
{
textBox1.Background = new SolidColorBrush(Colors.Green);
// its open, you want time till close
// validate close time is greater than open time
if (NyClose.CompareTo(NyOpens) > 0)
tillOpenClose = NyClose.Subtract(DateTime.UtcNow.TimeOfDay);
else
tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyClose)); // if the market closes at and earlier time, then the time till close, is the remaing time of this day, plus the time till close of the new day
}
else if ((IsTimeOfDayBetween(DateTime.UtcNow, dayStart, NyOpens)) == true) // if time is between start of day and open time
tillOpenClose = NyOpens.Subtract(DateTime.UtcNow.TimeOfDay);
else // it is between closetime and end of day
tillOpenClose = ((dayEnds.Subtract(DateTime.UtcNow.AddSeconds(-1).TimeOfDay)).Add(NyOpens)); // part remaining for this day plus new day, the extra second is to compensate the "dayEnds"
Console.WriteLine(tillOpenClose.ToString(@"hh\:mm\:ss"));
與「IsTimeOfDayBetween」功能應該是這樣的這樣的:
if (open.CompareTo(close) > 0) // if open time is greater (e.g. open: (20,0,0) close: (4,0,0))
{
if (timeNow.TimeOfDay.CompareTo(open) >= 0 || timeNow.TimeOfDay.CompareTo(close) <= 0)
return true;
}
else
{
if (timeNow.TimeOfDay.CompareTo(open) >= 0 && timeNow.TimeOfDay.CompareTo(close) <= 0)
return true;
}
return false;
編輯:改變的時間,直到接近,比較遺憾的是
編輯2:調整關閉時間早於開放時間
像魅力一樣工作。謝謝 ! – Suleman
@Suleman,沒問題......對不起,我剛剛編輯了答案,以考慮在新的一天的關閉時間。希望它正是你所需要的 – karkazz