0

因此,用户可以从 2 个日历中选择 2 个不同的日期,一个开始日期和一个结束日期,当他们单击add之间的日期时,包括所选日期在内的日期将被添加到数据库中,每个日期作为单独的记录。

这很好用,但是我不希望将周末添加到数据库中。

我已经更新了 datepicker http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerCustomCellRender.html的 UI, 但是如果用户选择 fri-mon 例如fri,sat,sun and mon将被添加到数据库中。如果 datyofweek 不是星期六或星期日,我试图只运行代码

 public ActionResult listHolidays(Holiday holiday, int? PersonId, string HolidayDate, string endDate)
        {
            DateTime startDates = Convert.ToDateTime(HolidayDate),
                     endDates = Convert.ToDateTime(endDate);

            while (startDates <= endDates)
            {
                if (startDates.DayOfWeek != DayOfWeek.Saturday || startDates.DayOfWeek != DayOfWeek.Sunday)
                {
                    Holiday holiday1 = new Holiday();
                    holiday1.PersonId = PersonId.Value;
                    holiday1.HolidayDate = startDates;

                    db.Holidays.AddObject(holiday1);
                    db.SaveChanges();


                     startDates = startDates.AddDays(1);
                }
            }

            return RedirectToAction("Index");
        }

有什么帮助吗?谢谢

4

4 回答 4

5

您需要使用 AND 而不是 OR:

if (startDates.DayOfWeek != DayOfWeek.Saturday && startDates.DayOfWeek != DayOfWeek.Sunday)

您当前的情况将永远为真。如果startDatesDayOfWeek.Saturday,则不是DayOfWeek.Sunday,反之亦然。

之后,您需要startDates = startDates.AddDays(1);if.

否则,您将有一个无限循环,因为一旦startDatesis DayOfWeek.Saturday,它将不再递增。

于 2012-12-10T15:13:25.410 回答
2

改变

if (startDates.DayOfWeek != DayOfWeek.Saturday || startDates.DayOfWeek != DayOfWeek.Sunday)

if (startDates.DayOfWeek != DayOfWeek.Saturday && startDates.DayOfWeek != DayOfWeek.Sunday)

然后你需要移动这条线

startDates = startDates.AddDays(1);

if块之外(否则,startDates如果日期是周末日期,变量将永远不会改变)。

于 2012-12-10T15:14:23.390 回答
1

就像您计算您选择的工作日数的替代解决方案一样

List<DateTime> allDates = New List<DateTime>();
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
    allDates.Add(date);
var days = allDates.Where(x => x.IsWeekday()).Count();

使用以下DateTime扩展名。

public static class DateTimeExtensions
{
  public static bool IsWeekday(this DateTime dt)
  {
   return dt.DayOfWeek != DayOfWeek.Sunday && dt.DayOfWeek != DayOfWeek.Saturday;
  }
}

根据我的评论,您可以将其扩展到IsWorkday是否为假期系统,并结合一些逻辑来检查当天是否为银行假期。

于 2012-12-10T15:27:49.147 回答
1

如果语句错误并且在错误的地方增加天数。

            while (startDates <= endDates)
            {
                if (startDates.DayOfWeek != DayOfWeek.Saturday **&&** startDates.DayOfWeek != DayOfWeek.Sunday)
                {
                    Holiday holiday1 = new Holiday();
                    holiday1.PersonId = PersonId.Value;
                    holiday1.HolidayDate = startDates;

                    db.Holidays.AddObject(holiday1);
                    db.SaveChanges();



                }

                **startDates = startDates.AddDays(1);**
            }
于 2012-12-10T15:15:42.187 回答