我有很多天,必须通过比较今天来选择下一个即将到来的日子, 这是我的代码段-
private string GetUpcomingDeliveryDay(string today, ModelSetting ObjModelSetting)
{
//string today = DateTime.Now.DayOfWeek.ToString(); //Tuesday
// daysOfDeliveries = ("Monday","Friday")
string[] daysOfDeliveries = Convert.ToString(ObjModelSetting.DeliveryDays).Split(',');
string nextDelivery = string.Empty;
return nextDelivery;
}
例如如果今天是星期一,并且它存在于数组中,则应该返回星期一,否则返回该数组中最近的一天。
我之前从未在日期和日期部分工作过,所以这对我来说越来越难了。 谢谢!
答案 0 :(得分:1)
如果您使用daysOfDeliveries
格式的DaysOfWeek
,那就容易了。因此,如果首先采用string
格式,则需要将其转换为Enum.DaysOfWeek
。剩下的将是一个简单的比较:
var days = daysOfDeliveries.Select(x => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), x)).ToArray();
DayOfWeek today = DateTime.Now.DayOfWeek;
var nextDelivery = days.Where(x => x >= today).FirstOrDefault();
请确保daysOfDeliveries
中的字符串符合Enum名称。
答案 1 :(得分:1)
您可以尝试以下操作:
private static string GetUpcomingDeliveryDay(string today, string[] days)
{
if (days.Length == 0)
{
return string.Empty;
}
if (days.Any(x => x == today.ToString()))
{
return today;
}
var day = string.Empty;
var allDays = Enum.GetValues(typeof(DayOfWeek));
var i = Array.IndexOf(allDays, Enum.Parse(typeof(DayOfWeek), today));
while (string.IsNullOrEmpty(day))
{
i++;
if (i >= allDays.Length)
{
i = 0;
}
if (days.Any(x => x == allDays.GetValue(i).ToString()))
{
day = allDays.GetValue(i).ToString();
}
}
return day;
}