如何获取两次约会之间的天数

How to get the number of days between two dates?

本文关键字:之间 约会 两次 何获取 获取      更新时间:2024-06-23

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

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

适合我-记住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");

我也面临同样的问题,为此成功地浪费了半天时间。并最终解决问题。您可以看到以下示例:

注意:不要忘记包含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>