我希望在范围之间知道另一天,如:
26-12-2017 5:45 pm。这是周一下午6点和周三下午6点。
请帮我解决。我只知道当天,但如何解决时间
答案 0 :(得分:0)
尝试这样的事情。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication59
{
class Program
{
static void Main(string[] args)
{
DateTime time = DateTime.ParseExact(("26-12-2017 5:45pm").ToUpper(),"dd-MM-yyyy h:mmtt", CultureInfo.InvariantCulture);
int dayOfWeek = (int)time.DayOfWeek;
DateTime saturdaySundayMidnight = time.AddDays(-dayOfWeek).Date;
TimeSpan timeOfWeek = time.Subtract(saturdaySundayMidnight);
TimeSpan startTime = new TimeSpan(1,17,45,0); //Monday 5:45PM
TimeSpan endTime = new TimeSpan(3,18,0,0); //Wednesday 6:00PM
if ((timeOfWeek >= startTime) && (timeOfWeek <= endTime))
{
Console.WriteLine("In Range");
}
}
}
}
上述代码在DayLight节省时间和周日早晨发生的标准时间之间切换时出现问题。所以使用周日/周一午夜更好。见下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication59
{
class Program
{
static void Main(string[] args)
{
DateTime time = DateTime.ParseExact(("26-12-2017 5:45pm").ToUpper(),"dd-MM-yyyy h:mmtt", CultureInfo.InvariantCulture);
int dayOfWeek = ((int)time.DayOfWeek - 1) % 7; //Monday day 0 instead of sunday
DateTime sundayMondayMidnight = time.AddDays(-dayOfWeek).Date;
TimeSpan timeOfWeek = time.Subtract(sundayMondayMidnight);
TimeSpan startTime = new TimeSpan(0,17,45,0); //Monday 5:45PM
TimeSpan endTime = new TimeSpan(2,18,0,0); //Wednesday 6:00PM
if ((timeOfWeek >= startTime) && (timeOfWeek <= endTime))
{
Console.WriteLine("In Range");
}
}
}
}