Calculating with TimeSpan and DateTime

本文关键字:DateTime and TimeSpan with Calculating | 更新日期: 2023-09-27 18:02:06

根据当前时间,我需要计算商店是否实际开放。到目前为止,打开时间被保存为TimeSpan:

public TimeSpan OpeningTime { get; set; }
public TimeSpan ClosingTime { get; set; }

我如何计算商店现在是否已经开门?我尝试了一些想法,但解决方案看起来相当繁琐。一个原因是需要在TimeSpanDateTime之间进行转换。TimeSpan是合适的开放时间格式吗?现在单独开一堂课会更有意义吗?

注意:工作日是分开处理的

Calculating with TimeSpan and DateTime

如果:

OpeningTime <= DateTime.Now.TimeOfDay <= ClosingTime

好吧,TimeSpan是两个时间之间的差异的度量,而不是实际时间

假设您使用TimeSpan来指示开放和关闭时间相对于午夜尝试

TimeSpan currentTime = DateTime.Now.TimeOfDay;   
bool isOpen = currentTime > OpeningTime && currentTime < ClosingTime;

试试这样写:

var timeOfDay = DateTime.Now.TimeOfDay;
if (timeOfDay >= OpeningTime && timeOfDay < ClosingTime)
{
    // open now!
}

你可以使用DateTime.Now.TimeOfDay,并比较你的2个时间跨度

    OpeningTime = new TimeSpan(9, 30, 0); // 9:30AM
    ClosingTime = new TimeSpan(17, 30, 0); // 5:30AM
    bool isOpen = DateTime.Now.TimeOfDay >= OpeningTime && DateTime.Now.TimeOfDay <= ClosingTime;
TimeSpan OpeningTime = new TimeSpan(8, 0, 0);
TimeSpan ClosingTime = new TimeSpan(16, 0, 0);
TimeSpan now = DateTime.Now - DateTime.Now.Date;
if (now > OpeningTime && now < ClosingTime)
{ 
    //...
}