我有一个DateTime选择器,它以以下格式生成textbox的日期和时间,

01 May, 2017 - 03:45 pm


现在,我需要检查此DateTime是否从现在起超过72小时。为此,我在Javascript中使用以下算法。

function chk() {
  try {
    debugger;
    var a = document.getElementById("txtdate").value;

    var adatepart = a.substring(0, 12).replace(",", "");

    //convert date part of txtbox
    var b = parseDate(adatepart);

    //getting number of hours of textbox from 1 jan 1970 midnight
    var seconds = new Date().getTime() / (3600 * 1000);

    //getting number of hours from 1 jan 1970
    var seconds1 = b.getTime() / (3600 * 1000);

    //adding additional hours and 12 hours if it's past noon
    seconds1 += parseInt(a.substring(15, 17)) + (a.substring(21, 23) == "pm" ? 12 : 0);
    var diff = seconds1 - seconds;
    if (diff > 72 || diff < 0) {
      alert("The selected date and time cannot be more than 72 hours from now");
    }
  } catch (err) {
    alert(err.message);
  }
}

function parseDate(input) {
  var map = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
  input = input.split(" ");
  return new Date(input[2], input[1] in map ? map[input[1]] : input[1] - 1, input[0]);
}


该算法工作正常。但我相信,有一种更短的方法可以直接比较date.nowdatetime中的textbox。也许通过jQuery。有没有更短的方法?

最佳答案

可能有帮助

diff = (parseDate(e.substring(0, 12).replace(",", "")).getTime() / (3600 * 1000) + parseInt(e.substring(15, 17)) + (e.substring(21, 23) == "pm" ? 12 : 0)) - new Date().getTime() / (3600 * 1000);

if (diff < -72) {
//Your code
}

关于javascript - 检查输入的日期时间从现在开始是否超过72小时?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43513893/

10-11 01:46