Check if DatetimeOffset is between 10 PM (today) and 2 AM (next day)

108 Views Asked by At

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)
{
}
1

There are 1 best solutions below

0
SyndRain On

In your code if the currentDateInCST is 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 when kind is not set to UTC.

You can get the current CST Datetime by using TimeZoneInfo.ConvertTime.

var currentDateInCST = TimeZoneInfo.ConvertTime(DateTime.Now,
        TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
var nextDay = currentDateInCST.Date.AddDays(1);
var startDate = nextDay.AddHours(-2);
var endDate = nextDay.AddHours(2);

if (currentDateInCST > startDate && currentDateInCST < endDate)
{
    //do stuff
}

If what you actually want is to see if the currentCST time is between 10pm and 2am within the timezone offset, simply compare the Hour of the currentDateInCST.

var currentDateInCST = TimeZoneInfo.ConvertTime(DateTime.Now,
        TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));

if(currentDateInCST.Hour > 22 && currentDateInCST.Hour < 2)
{
    //do stuff
}

Finally, to answer how to set the DateTimeOffset to CST and use it to compare:

var nextDay = currentDateInCST.Date.AddDays(1);
DateTimeOffset startDate = new DateTimeOffset(nextDay.AddHours(-2),
                  TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(nextDay.AddHours(-2)));
DateTimeOffset endDate = new DateTimeOffset(nextDay.AddHours(2),
                  TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(nextDay.AddHours(2)));
if (currentDateInCST > startDate && currentDateInCST < endDate)
{
    //do stuff
}