public static DateTime ConvertTimeFromUtcToEt(DateTime p_dateTimeUtc) { TimeZoneInfo utcZone = TimeZoneInfo.Utc; TimeZoneInfo?estZone = null; try { estZone = Utils.FindSystemTimeZoneById(TimeZoneId.EST); } catch (Exception e) { Utils.Logger.Error(e, "Exception because of TimeZone conversion "); return(DateTime.MaxValue); } return(TimeZoneInfo.ConvertTime(p_dateTimeUtc, utcZone, estZone)); }
// it is important that p_timeUtc can be a Time and it is in UTC. Convert it to ET to work with it. public static bool DetermineUsaMarketTradingHours(DateTime p_timeUtc, out bool p_isMarketTradingDay, out DateTime p_openTimeUtc, out DateTime p_closeTimeUtc, TimeSpan p_maxAllowedStaleness) { p_openTimeUtc = p_closeTimeUtc = DateTime.MinValue; p_isMarketTradingDay = false; TimeZoneInfo utcZone = TimeZoneInfo.Utc; TimeZoneInfo?estZone = null; try { estZone = Utils.FindSystemTimeZoneById(TimeZoneId.EST); } catch (Exception e) { Utils.Logger.Error(e, "Exception because of TimeZone conversion "); return(false); } DateTime timeET = TimeZoneInfo.ConvertTime(p_timeUtc, utcZone, estZone); if (timeET.DayOfWeek == DayOfWeek.Saturday || timeET.DayOfWeek == DayOfWeek.Sunday) { p_isMarketTradingDay = false; return(true); } List <Tuple <DateTime, DateTime?> >?holidaysAndHalfHolidays = GetHolidaysAndHalfHolidaysWithCloseTimesInET(p_maxAllowedStaleness); if (holidaysAndHalfHolidays == null || holidaysAndHalfHolidays.Count == 0) { Logger.Error("holidaysAndHalfHolidays are not recognized"); return(false); // temporarily off } DateTime openInET = new DateTime(timeET.Year, timeET.Month, timeET.Day, 9, 30, 0); DateTime closeInET; var todayHoliday = holidaysAndHalfHolidays.FirstOrDefault(r => r.Item1 == timeET.Date); if (todayHoliday == null) // it is a normal day, not holiday: "The NYSE and NYSE MKT are open from Monday through Friday 9:30 a.m. to 4:00 p.m. ET." { p_isMarketTradingDay = true; closeInET = new DateTime(timeET.Year, timeET.Month, timeET.Day, 16, 0, 0); } else { // if it is a holiday or a half-holiday (that there is trading, but early close) p_isMarketTradingDay = (todayHoliday.Item2 != null); // Item2 is the CloseTime (that is for half-holidays) if (todayHoliday.Item2 == null) { p_isMarketTradingDay = false; return(true); } else { p_isMarketTradingDay = true; closeInET = (DateTime)todayHoliday.Item2; // yes, halfHolidays are in ET } } if (!p_isMarketTradingDay) { return(true); } p_openTimeUtc = TimeZoneInfo.ConvertTime(openInET, estZone, utcZone); p_closeTimeUtc = TimeZoneInfo.ConvertTime(closeInET, estZone, utcZone); return(true); }