如何在时间间隔内执行操作

时间:2019-04-16 10:37:45

标签: c# xamarin

我正在尝试根据一天中的时间更改标签的文本。

Label OpenClosedLabel = new Label();
TimeSpan T1 = new TimeSpan(13, 00, 00);
TimeSpan T2 = new TimeSpan(00, 00, 00);

现在,如果DateTime.Today.TimeOfDayT1T2内,则标签应为“打开”,否则应为“关闭”。

我已经尝试过了,但是不起作用:

if (DateTime.Today.TimeOfDay >= T1 && DateTime.Today.TimeOfDay <= T2)
{ 
    OpenClosedLabel.Text = "Open";
} 
else
{ 
    OpenClosedLabel.Text = "Closed";
}

1 个答案:

答案 0 :(得分:1)

DateTime.Today.TimeOfDay仅会给您日期,而

DateTime.Now.TimeOfDay也会为您提供时间数据。

所以,我会这样做:

Label OpenClosedLabel = new Label();
TimeSpan T1 = new TimeSpan(13, 00, 00);
TimeSpan T2 = new TimeSpan(23, 59, 59);
var Now = DateTime.Now.TimeOfDay;
OpenClosedLabel.Text = (Now >= T1 && Now <= T2) ? "Open" : "Closed";