我需要一种方法来检查日期和时间是否介于特定日期和时间间隔之间(例如:我的项目中有一个时间间隔,截止时间为星期五18:00:00~星期六18:00 :00)。我需要一种方法来检查当前日期和时间是否在c#
中的该范围之间答案 0 :(得分:0)
这样的事情:
public static void Main(string[] args)
{
string interval = "07/28/2017 6:00:00 PM-07/29/2017 6:00:00 PM";
string[] parts = interval.Split(new char[] { '-' });
DateTime start = Convert.ToDateTime(parts[0]);
DateTime end = Convert.ToDateTime(parts[1]);
DateTime currentTime = DateTime.Now;
if (currentTime > start && currentTime < end)
Console.WriteLine("Within range");
else
Console.WriteLine("Not within range");
Console.ReadLine();
}
您需要进行错误处理(我在这里没有做过),例如查看字符串中的日期是否格式正确,是否有两个日期,是否开始&lt;结束等。
答案 1 :(得分:0)
由于你没有包含任何代码,这应该可以帮助你。
假设您没有在Date
中传递web.config
,但只是按照提及的时间间隔friday 18:00:00~saturday 18:00:00
以您找到的任何方式获取值
DateTime today = DateTime.Now;
TimeSpan start = new TimeSpan(18, 0, 0);
TimeSpan end = start; //setting the same value as your start and end time is same
DateTime fridayStartCheck = new DateTime();
DateTime saturdayEndCheck = new DateTime();
if (today.DayOfWeek == DayOfWeek.Friday)
{
fridayStartCheck = DateTime.Parse(today.ToShortDateString());
fridayStartCheck += start;
saturdayEndCheck = DateTime.Parse(today.AddDays(+1).ToShortDateString());
saturdayEndCheck += end;
}
if (today.DayOfWeek == DayOfWeek.Saturday)
{
fridayStartCheck = DateTime.Parse(today.AddDays(-1).ToShortDateString());
fridayStartCheck += start;
saturdayEndCheck = DateTime.Parse(today.ToShortDateString());
saturdayEndCheck += end;
}
if (today >= fridayStartCheck && today <= saturdayEndCheck )
{
//add maintenance code
}
编辑1:
再次假设,正如您在friday 18:00:00~saturday 18:00:00
文件中传递web.config
一样,我建议您将值存储为Friday 18:00:00~Saturday 18:00:00
(将当天的第一个字母大写)。然后,您可以在DayOfWeek
类型的变量中获取这些值,并使用以下代码:
DateTime today = DateTime.Now;
string IntervalPeriod = "Friday 18:00:00~Saturday 18:00:00";
string SDay = IntervalPeriod.Split('~')[0].Split(' ')[0];
string STime = IntervalPeriod.Split('~')[0].Split(' ')[1];
string EDay = IntervalPeriod.Split('~')[1].Split(' ')[0];
string ETime = IntervalPeriod.Split('~')[1].Split(' ')[1];
DayOfWeek StartDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), SDay);
DayOfWeek EndDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), EDay);
TimeSpan start = TimeSpan.Parse(STime);
TimeSpan end = TimeSpan.Parse(ETime);
DateTime StartCheck = new DateTime();
DateTime EndCheck = new DateTime();
if (today.DayOfWeek == StartDay)
{
StartCheck = DateTime.Parse(today.ToShortDateString());
StartCheck += start;
EndCheck = DateTime.Parse(today.AddDays(+1).ToShortDateString());
EndCheck += end;
}
if (today.DayOfWeek == EndDay)
{
StartCheck = DateTime.Parse(today.AddDays(-1).ToShortDateString());
StartCheck += start;
EndCheck = DateTime.Parse(today.ToShortDateString());
EndCheck += end;
}
if (today >= StartCheck && today <= EndCheck)
{
//add maintenance code
}
现在,如果它遵循模式Startday starttime~Endday endtime
,则可以传递任何间隔。 此代码不包含错误检查。因此,如果你使用它并需要一些修改,请告诉。