PHP计算两个日期内的天数, Javascript 计算两个日期内的天数, Finding the number of days between two dates

 

PHP 版

function dateDiff($start, $end) {
  $start_ts = strtotime($start);
  $end_ts = strtotime($end);
  $diff = $end_ts - $start_ts;
  return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';
 
//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days'; 

或者

<?php
    $from=date_create(date('Y-m-d'));
    $to=date_create("2013-03-15");
    $diff=date_diff($to,$from);
    print_r($diff);
    echo $diff->format('%R%a days');
?>

 

Javscript 版

// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format (which does no error checking)
function parseDate(str) {
    var mdy = str.split('/');
    return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function datediff(first, second) {
    // Take the difference between the dates and divide by milliseconds per day.
    // Round to nearest whole number to deal with DST.
    return Math.round((second-first)/(1000*60*60*24));
}

alert(datediff(parseDate(first.value), parseDate(second.value)));

 

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

 

或者用 Moment 库

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

 

如果要包括开始的那一天的话,可以:

a.diff(b, 'days')+1   // =2

 

也可以计算当月的天数:

moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31

 

 

本文:PHP计算两个日期内的天数, Javascript 计算两个日期内的天数, Finding the number of days between two dates

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.