使用时间检查是否在星期五到星期天之间,然后忽略
本文关键字:之间 星期天 然后 星期五 时间 检查 是否 | 更新日期: 2023-09-27 18:29:54
我正在检查当前时间,如果是周五下午3点到周日晚上7点,则忽略它。代码是有效的,但是有更好更简单的方法吗?
Boolean iCheck = true;
DateTime iCurTime = DateTime.Now;
//if its friday and 3pm or after don't check
if (iCurTime.ToString("ddd") == "Fri") {
if (iCurTime.TimeOfDay >= new TimeSpan(15, 0, 0)) {
iCheck = false;
}
}
//if its saturday dont check
if (iCurTime.ToString("ddd") == "Sat") {
iCheck = false;
}
//if its sunday and less than 7pm dont check
if (iCurTime.ToString("ddd") == "Sun") {
if (iCurTime.TimeOfDay <= new TimeSpan(19, 0, 0)) {
iCheck = false;
}
}
不确定这是否比您的解决方案更好,但它可以
//use Sunday_Monday midnight as reference
TimeSpan friday_3PM = new TimeSpan(4, 15, 0, 0);
TimeSpan sunday_7PM = new TimeSpan(6, 19, 0, 0);
DateTime now = DateTime.Now;
TimeSpan timeSpan = now - now.AddDays(-1 * (((int)now.DayOfWeek + 6) % 7)).Date;
if((timeSpan < friday_3PM) || (timeSpan > sunday_7PM))
{
}
我喜欢LINQ。。。
var dtl = new List<DateTime>();
dtl.Add(DateTime.Now);
var DaysOfWeekToInclude = dtl.Where(
d => d.DayOfWeek == DayOfWeek.Friday ||
d.DayOfWeek != DayOfWeek.Saturday ||
d.DayOfWeek == DayOfWeek.Sunday);
var FirstFilter = DaysOfWeekToInclude.Where(
p =>
p.DayOfWeek == DayOfWeek.Friday && p.Hour <= 15);
var SecondFilter = FirstFilter.Where(
p => p.DayOfWeek == DayOfWeek.Sunday && p.Hour > 19);
var filtered = SecondFilter.First();