3

我需要计算两个日期之间的天数。我已经检查了给出这个链接的代码 如何使用 JavaScript 计算两个日期之间的天数?.

在此示例中,如果输入 2012,02,29 和 2012,03,01,则输出为 3。实际答案应为 1。这些还有其他方法可以计算 2 个日期之间的天数吗?

4

2 回答 2

11

对我有用-记住 JS 中的月份从 0 开始,所以这里是 2012 年 2 月 29 日到 3 月 1 日

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2012, 1, 29, 12, 0, 0, 0); // 29th of Feb at noon your timezone
var secondDate = new Date(2012, 2, 1, 12, 0, 0, 0); // 1st of March at noon

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
console.log(firstDate, "to", secondDate, "\nDifference: " + diffDays + " day");

于 2012-08-02T05:16:39.343 回答
0

我也遇到了同样的问题,成功地为此浪费了半天时间。终于解决了问题。你可以看下面的例子:

注意:不要忘记包含 jquery 脚本:

$("#ToDate").change(function() {
  var start = new Date($('#FromDate').val());
  var end = new Date($('#ToDate').val());
  var diff = new Date(end - start);
  var days = 1;
  days = diff / 1000 / 60 / 60 / 24;
  if (days == NaN) {
    $('#TotalDays').val(0);
  } else {
    $('#TotalDays').val(days + 1);
  }
})
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>


<form action="{{route('leave.store')}}" method="post" class="form-horizontal">
  @csrf
  <div class="card-body">
    <h4 class="card-title">Apply Leave</h4>
    <div class="form-group row">
      <label for="fname" class="col-sm-3 text-right control-label col-form-label">Leave type</label>
      <div class="col-sm-9">
        <input type="text" name="leave_type" class="form-control" id="fname" placeholder="Leave type">
      </div>
    </div>
    <div class="form-group row">
      <label for="lname" class="col-sm-3 text-right control-label col-form-label">Date from</label>
      <div class="col-sm-4">
        <input type="date" min="{{date('Y-m-d')}}" name="from" class="form-control" id="FromDate">
      </div>
      <div class="col-sm-4">
        <input type="date" name="to" class="form-control" id="ToDate">
      </div>
    </div>
    <div class="form-group row">
      <label for="fname" class="col-sm-3 text-right control-label col-form-label">Days</label>
      <div class="col-sm-9">
        <input type="text" name="days" class="form-control" id="TotalDays" placeholder="Number of leave days">
      </div>
    </div>
    <div class="form-group row">
      <label for="fname" class="col-sm-3 text-right control-label col-form-label">Reason</label>
      <div class="col-sm-9">
        <textarea type="text" name="reason" class="form-control" placeholder="Reason">
                                        </textarea></div>
    </div>
  </div>
  <div class="border-top">
    <div class="card-body">
      <button type="submit" class="btn btn-dark">Apply</button>
    </div>
  </div>
</form>

于 2019-04-10T10:17:29.463 回答