我从数据库中的数据中得到以下场景:
Current logic
Monday 08:00 - 17:00
Tuesday 08:00 - 15:00
Tuesday 17:00 - 23:00
Wednesday 08:00 - 03:00 (overflow next day)
Thursday 08:00 - 03:00 (overflow next day)
Friday 09:00 - 11:00
public class WorkTimeFrameModel
{
/// <summary>
/// Gets or sets the raw value of the day of the week enum.
/// </summary>
public int DayOfWeek { get; set; }
/// <summary>
/// Gets or sets the start of the time frame as a TimeSpan.
/// </summary>
public TimeSpan StartTime { get; set; }
/// <summary>
/// Gets or sets the end of the time frame as a TimeSpan.
/// </summary>
public TimeSpan EndTime { get; set; }
/// <summary>
/// Gets or sets the enum value of the DayOfWeek property.
/// </summary>
public DayOfWeek DayOfWeekEnum
{
get { return (DayOfWeek)DayOfWeek; }
set { DayOfWeek = (int)value; }
}
}
目前,我编写的代码可以在当天无关紧要时确定溢出并且它可以完美运行:
internal bool IsWithinWorkingTimes(IReadOnlyCollection<ApplicationSettings> timeSettings, DateTime dateTime)
{
var startDate = dateTime.Date;
var endDate = dateTime.Date;
//We should have only 2 records, if not we cannot do an accurate calculation on the start or end time.
if (timeSettings is not { Count: 2 })
return false;
if (!TimeSpan.TryParse(timeSettings.FirstOrDefault(x => x.Key.EndsWith("StartTime"))?.StringValue, out var start))
return false;
if (!TimeSpan.TryParse(timeSettings.FirstOrDefault(x => x.Key.EndsWith("EndTime"))?.StringValue, out var end))
return false;
startDate = startDate.Date + start;
endDate = endDate.Date + end;
if (start > end)
{
return dateTime > startDate || dateTime < endDate;
}
return dateTime >= startDate && dateTime <= endDate;
}
但是现在对于特定的日子,我如何确定当前时间是在第二天还是第一天,如上:
我知道这种情况实际上是一个设计缺陷,你应该禁止用户超过 00:00,但不幸的是设计无法更改,因为我们不管理前端,所以我现在在代码中的 api 中修复它可以在这个阶段管理。