JavaScript中两个日期之间的天数

时间:2018-02-20 15:59:45

标签: javascript

我写了这个函数,但仍然无效:

function myfunction(){
    var Date_debut = $("#Date_debut").datepicker({ dateFormat: 'dd/mm/yyyy' }).val();

    var Date_fin = $("#Date_fin").datepicker({ dateFormat: 'dd/mm/yyyy' }).val();

    alert(Date_fin);
    var timeDiff = Math.abs(Date_fin- Date_debut);
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

    document.getElementById("Nomber_de_jours").value =diffDays;
}

3 个答案:

答案 0 :(得分:0)

试试这个



var Date_debut = $("#Date_debut").datepicker({
  dateFormat: 'dd/mm/yy'
});

var Date_fin = $("#Date_fin").datepicker({
  dateFormat: 'dd/mm/yy'
}).change(function() {
   myfunction();
});

function myfunction() {
  var days = (Date_fin.datepicker('getDate') - Date_debut.datepicker('getDate')) / 1000 / 60 / 60 / 24;
  document.getElementById("Nombre_de_jours").innerHTML = "Number of days: " + days;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>TEST Date</title>
  <link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
  <script src="https://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>

  Start Date: <input type="text" id="Date_debut" /><br><br> End Date: <input type="text" id="Date_fin" /><br><br>
  <p id="Nombre_de_jours"></p>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要从jQueryUI对象中获取日期。

像这样:

$("#Date_debut").datepicker({ dateFormat: 'dd/mm/yy' });
$("#Date_fin").datepicker({ dateFormat: 'dd/mm/yy' });

function getDaysBetweenDates() {
    var debutDate = $("#Date_debut").datepicker('getDate');
    var finDate = $("#Date_fin").datepicker('getDate');
    $('#Nomber_de_jours').html('Days between: ' + Math.abs(finDate - debutDate) / (1000*60*60*24));
}

Example CodePen

答案 2 :(得分:0)

您可以使用http://momentjs.com/ 你可以这样做:

nomber_de_jours = moment(debutDate).diff(moment(finDate), 'days');