使用JavaScript计算时差时出现问题

时间:2019-07-17 08:36:02

标签: javascript date

在使用JavaScript计算两个日期之间的时差时,我遇到了一些问题。我在下面提供我的代码。

在这里,我有cutoff time and dep_time的值。我必须使用dep_date计算今天的日期,如果今天的日期和时间在截止时间之前,则它将返回true,否则返回false。就我而言,它可以在Chrome中正常工作,但对于相同的功能,它不能在Firefox中工作。我需要它才能在所有浏览器上正常工作。

function checkform() {
  var dep_date = $("#dep_date1").val(); //07/27/2019
  var cut_offtime = $("#cutoff_time").val(); //1
  var dep_time = $("#dep_time").val(); //6:00pm
  var dep_time1 = dep_time.replace(/[ap]/, " $&");
  var todayDate = new Date();
  var todayMonth = todayDate.getMonth() + 1;
  var todayDay = todayDate.getDate();
  var todayYear = todayDate.getFullYear();
  if (todayDay < 10) {
    todayDay = "0" + todayDay;
  }
  if (todayMonth < 10) {
    todayMonth = "0" + todayMonth;
  }
  //console.log('both dates',todayMonth,todayDay,todayYear);
  var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
  var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
  var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
  console.log("both dates", dep_date, todayDateText);
  if (inputToDate >= todayToDate) {
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? "pm" : "am";
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? "0" + minutes : minutes;
    var strTime = hours + ":" + minutes + " " + ampm;
    var timeStart = new Date(todayDateText + " " + strTime);
    var timeEnd = new Date(dep_date + " " + dep_time1);
    var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
    var minutes = diff % 60;
    var hours = (diff - minutes) / 60;
    console.log("hr", hours);
    if (parseInt(hours) > parseInt(cut_offtime)) {
      return true;
    } else {
      alert("You should book this trip before " + cut_offtime + " hr");
      return false;
    }
  } else {
    alert("You should book this trip before " + cut_offtime + " hr");
    return false;
  }
}

1 个答案:

答案 0 :(得分:0)

部分问题在这里:

var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));

第一行生成类似“ 07-17-2019”的字符串。下一个将其更改为“ 07 17 2019”,并将其提供给内置解析器。该字符串不是ECMA-262支持的格式,因此解析取决于实现。

Chrome和Firefox返回的日期为2019年7月17日,Safari返回的日期无效。

解析一个字符串以获取值,然后生成另一个要由内置解析器解析的字符串是没有意义的。只需将第一组值直接提供给Date构造函数即可:

var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);

在所有支持ECMAScript的浏览器中均可使用。

类似地:

var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);

似乎是复制日期并将秒和毫秒设置为零的冗长而脆弱的方法。下面正是用更少的代码做到了这一点:

var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);

使用

var timeStart = new Date(todayDateText + " " + strTime)

将这些更改应用于您的代码会得到类似的信息

function parseMDY(s) {
  var b = s.split(/\D/);
  return new Date(b[2], b[0]-1, b[1]);
}

function formatDate(d) {
  return d.toLocaleString(undefined, {
    day: 'numeric',
    month: 'short',
    year: 'numeric'
  });
}

// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
  
  // Helper
  function z(n) {
    return (n<10?'0':'') + n;
  }
  
  // Convert dep_date to Date
  var depD = parseMDY(dep_date);

  // Get the departure time parts
  var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
  var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
  var depMin = +dtBits[1];
  
  // Set the cutoff date and time
  var cutD = new Date(depD);
  cutD.setHours(depHr, depMin, 0, 0);

  // Get current date and time
  var now = new Date();
  
  // Create cutoff string
  var cutHr = cutD.getHours();
  var cutAP = cutHr > 11? 'pm' : 'am';
  cutHr = z(cutHr % 12 || 12);
  cutMin = z(cutD.getMinutes());
  var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
  var cutDStr = formatDate(cutD);
  
  // If before cutoff, OK
  if (now < cutD) {
    alert('Book before ' + cutStr + ' on ' + cutDStr);
    return true;
  
  // If after cutoff, not OK
  } else {
    alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
    return false;
  }
}

// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');

这可以在某种程度上重构您的代码,但是希望可以显示如何改进它并修复解析错误。