Below is the code that I have to check if currentDateInCST is between 10 PM and 2 AM (next day) in Central Standard Time. How do I make the startDate and endDate to be Central Standard Time ?
public DateTimeOffset GetTimeByTimeZone(DateTimeOffset? date, string windowsTimeZone)
{
var timeZone = PlatformTimeZoneMapper.GetTimeZoneIdForPlatform(windowsTimeZone);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
return effectiveDate.Value.ToOffset(timeZoneInfo.GetUtcOffset(date.Value));
}
var currentDateInCST = GetTimeByTimeZone(DateTimeOffset.Now, "Central Standard Time");
var startDate = new DateTimeOffset(currentDateInCST.Year, currentDateInCST.Month, currentDateInCST.Day, 22, 0, 0, new TimeSpan(0, 0, 0));
var tomorrowsDate = currentDateInCST.DateTime.AddDays(1);
var endDate = new DateTimeOffset(tomorrowsDate.Year, tomorrowsDate.Month, tomorrowsDate.Day, 2, 0, 0, new TimeSpan(0, 0, 0));
if (currentDateInCST >= startDate && currentDateInCST <= endDate)
{
}
In your code if the
currentDateInCSTis at 1am, it will look for 2AM of the next day (which is over 24 hours away). I doubt this is what you want. However if it is, I would say in this case it is easier to compare DateTimes, which is independent to TimeZones whenkindis not set to UTC.You can get the current CST Datetime by using
TimeZoneInfo.ConvertTime.If what you actually want is to see if the currentCST time is between 10pm and 2am within the timezone offset, simply compare the
Hourof the currentDateInCST.Finally, to answer how to set the DateTimeOffset to CST and use it to compare: