如何计算javascript中两个日期时间之间的天数?

时间:2014-03-21 06:11:19

标签: javascript datetime

如何计算两个日期之间的天数?
请看下面的代码:

<script type="text/javascript">
    // how to count days between two date time ?
    var a= '2014-03-21 12:00:12';
    var b = '2014-05-11 18:00:00';
    function days_diff(a,b){
        // .....
        // ..... placeholder ....
        // ..... placeholder ....
        // ..... placeholder ....
        // ..... placeholder ....
        // ..... placeholder ....
        // .....
        // var days = days_a - days_b;
        return days;
    }

</script>   

3 个答案:

答案 0 :(得分:3)

  <script>
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var firstDate = new Date(2008,01,12);
    var secondDate = new Date(2008,01,22);
    var diffDays = Math.round(Math.abs((firstDate.getTime()-secondDate.getTime())/(oneDay)));
  </script>

答案 1 :(得分:1)

试试这个

<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

<script>
  alert(datediff("day", first, second)); // what goes here?
</script>

您的功能

function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function daydiff(first, second) {
    return (second-first)/(1000*60*60*24)
}

alert(daydiff(parseDate($('#first').val()), parseDate($('#second').val())));

答案 2 :(得分:1)

这可能对你有所帮助......

var Date1 = new Date (2012, 6, 12);
var Date2 = new Date (2014, 3, 16);
var Days = Math.floor((Date2.getTime() - Date1.getTime())/(1000*60*60*24));