I would suggest writing a simple function for each trading session that takes a DateTime and returns a bool indicating whether it will open at that time.
var sydneyOpen = new TimeSpan(17, 0, 0); var sydneyClose = new TimeSpan(2, 0, 0); Func<DateTime, bool> isOpenInSydney = d => (d.TimeOfDay > sydneyOpen || d.TimeOfDay < sydneyClose);
Then put them in Dictionary<TradingSession, Func> , as it is for general search ...
var marketHours = new Dictionary<TradingSession, Func<DateTime, bool>>(); marketHours.Add(TradingSession.Sydney, isOpenInSydney);
And then your existing method simply selects the appropriate function for the given TradingSession and applies it
public bool IsTradingSession(TradingSession tradingSession, DateTime currentTime) { var functionForSession = marketHours[tradingSession]; return functionForSession(currentTime); }
I donβt think you need UTC time here, as long as your application only works in one time zone, but summer savings can cause problems.
A good way to take into account the problem of trading sessions that span two days, and not just one day, is to write an assistant who accurately considers whether it is an βintradayβ trading session and applies a different rule for you:
private bool IsBetween(DateTime now, TimeSpan open, TimeSpan close) { var nowTime = now.TimeOfDay; return (open < close // if open is before close, then now must be between them ? (nowTime > open && nowTime < close) // otherwise now must be *either* after open or before close : (nowTime > open || nowTime < close)); }
and then
var sydneyOpen = new TimeSpan(17, 0, 0); var sydneyClose = new TimeSpan(2, 0, 0); Func<DateTime, bool> isOpenInSydney = d => IsBetween(d, sydneyOpen, sydneyClose);