如何在MVC C#中与2个日期进行2次比较和验证?

时间:2017-08-17 12:31:04

标签: c# asp.net-mvc validation

如何比较和验证两次? 我的方案是我需要添加各种日程安排。假设person 1 has schedules on today 18/08/2017 as Sch1: 0800-1600 and sch2:2200-0600sch1 starts and ends on same daysch2 starts on 18/08/2017 and ends on 19/08/2017 6am. 现在,当我尝试编辑计划结束时间时,我想添加2个验证,计划结束时间必须大于开始时间,并且还必须大于当前系统时间。如何验证这两个?当我在24小时后添加验证然后结束时间时,需要时间为2017年8月19日上午1点至凌晨3点,低于18/08 / 2017年的2000,2100(晚上8点,9点)。

我在下面的验证编码

if ( D.ScheduleEndTime != T.EndTime && D.ScheduleEndTime < Time)
{
    return Json(new { success = "fail", message = "End Time must be greater than current time!!!" }, JsonRequestBehavior.AllowGet);
}
else if (D.ScheduleEndTime != T.EndTime && D.ScheduleEndTime < T.StartTime)
{
   return Json(new { success = "fail", message = "End Time must be greater than start time!!!" }, JsonRequestBehavior.AllowGet);
}

在上面的代码D&amp; T. D表示编辑时输入的值,T表示数据库中表格的值

1 个答案:

答案 0 :(得分:0)

您没有提供有关您正在使用的数据类型的任何信息,但听起来您使用的是自定义日期时间对象而不是日期时间数据类型?

因此,每个自定义日期时间对象都具有类似于以下结构的内容:

custom_datetime:
 - string Date (ie: 18/08/2017)
 - int startTime (ie: 2200)
 - int endTime (ie: 0600)

在这种情况下,它可能是这样的......

// Temp variable to manipulate, instantiated to passed in custom_datetime D.
custom_datetime temp = D;
// First check if the passed in date time is different than date time stored
if ((temp.Date != T.Date) || ((temp.Date == T.Date) && (temp.endTime != T.endTime))) {
    // Then check if the endTime is less than the startTime
    // If it is, then the end time is the next day so increment the date in temp variable. Now use temp variable to do rest of the checks.
    if (temp.endTime < temp.startTime) {
        temp.Date++; // Increment to next day, so 18/08/2017 becomes 19/08/2017
    }

    //Check if passed in date < stored date, if it is, then it will also be less than startTime so return error.
    if (temp.Date < T.Date) { 
        return Json(new { success = "fail", message = "End Time must be greater than current time!!!" }, JsonRequestBehavior.AllowGet);
    }
    //Check if the passed in date is the same as the stored date. If it is, make sure the endTime is greater than the stored startTime
    else if ((temp.Date == T.Date) && (temp.endTime <= T.startTime)) {
        return Json(new { success = "fail", message = "End Time must be greater than current time!!!" }, JsonRequestBehavior.AllowGet);
    }
    //Check if the passed in date < current system date or if the passed in date == current system date but the endTime <= the current time.
    else if ((temp.Date < Time.Date) || ((temp.Date == Time.Date) && (temp.endTime <= Time.Time)) {
        return Json(new { success = "fail", message = "End Time must be greater than current time!!!" }, JsonRequestBehavior.AllowGet);
    }
}

代码实际上并不起作用,但希望它能让您了解自己可以做的事情。需要更多信息才能给出确切答案。