如何检查已用时间

时间:2012-07-05 07:33:40

标签: javascript jquery asp.net html time

我通过拖动html表格单元格来获得startTime 13:30:00 endTime 14:15:00(24小时格式)。     在hiddenfield中,我存储值starttime和endtime

                var hidStartTime=13:30:00;
                var hidEndTime=14:15:00;

我必须检查用户是否将starttime和endtime与当前客户端机器时间进行比较,然后必须生成警报(“您不能允许修改过去时间的约会。”); 我该如何检查

            var todaysDate = new Date();
            var currentHour = todaysDate.getHours();
            var currentMinutes = todaysDate.getMinutes();

            if (currentHour < endTimeHour)
            {
                alert("You can not allow to fix appointment for past time.");
                return false;
            }

2 个答案:

答案 0 :(得分:2)

假设日期将是今天,您可以使用开始和结束时间创建Date对象,然后将它们与当前日期进行比较,如下所示。

var currDate  = new Date();
var startDate = setTime(hidStartTime);
var endDate   = setTime(hidEndTime);

// given an input string of format "hh:mm:ss", returns a date object with 
// the same day as today, but the given time.
function setTime(timeStr) {
    var dateObj = new Date();          // assuming date is today
    var timeArr = timeStr.split(':');  // to access hour/minute/second

    var hour    = timeArr[0]; 
    var minute  = timeArr[1];
    var second  = timeArr[2];

    dateObj.setHours(hour);
    dateObj.setMinutes(minute);
    dateObj.setSeconds(second);
    return dateObj;
}

// now we can subtract them (subtracting two Date objects gives you their 
// difference in milliseconds)
if (currDate - startDate < 0 || currDate - endDate < 0) {
    alert("Unfortunately, you can't schedule a meeting in the past. 
             We apologize for the inconvenience.");
}

答案 1 :(得分:0)

您可以像这样比较2个Date对象:

// Get current date on the client machine
var currentDateTime = new Date(); // "Thu, 05 Jul 2012 08:05:57 GMT"

// Now if you have a date string of 8:30 on the same day
var endDateTime = Date.parse("Thu, 05 Jul 2012 08:30:00 GMT");

if (currentDateTime > endDateTime) {
  alert("...");
}

困难的部分可能是将日期字符串组成一种格式,可以通过函数Date.parse()来理解