PHP日期在6个月内

时间:2017-01-10 08:24:16

标签: php date comparison

如何确定给定日期(即4月4日)是否在将来的6个月内?

例如:

4/2017 true
8/2017 false
5/2017 true

我现在有:

$datum = explode(': ', $given_date); // Separate date from string
$datum = str_replace('/', '-', $datum[1]); // Given format month/year
$datum = strtotime('01-'.$datum); // Given only month/year
$limit_datum = strtotime('+6 months');

但我现在倾斜了,无法比较它......

3 个答案:

答案 0 :(得分:4)

使用DateTime,它变得非常简单:

$now = new DateTime();
$input = DateTime::createFromFormat('m/Y', '4/2017');

$diff = $input->diff($now); // Returns DateInterval

// m is months
$lessThanSixMonths = $diff->y === 0 && $diff->m < 6;  // true

请参阅DateIntervalDateTime

答案 1 :(得分:0)

你需要做这样的事情

$todayDate = time();
$date_6_months = strtotime("+6 months");
$givenDate = strtotime($date);
if ($givenDate > $todayDate && $givenDate < $date_6_months){
     put your code
}

答案 2 :(得分:-1)

编辑:我改变了以前的错误脚本。在这个中你可以比较两个日期的字符串

    $given_date= "...."; //set given date (m/Y)
    $current_date = date("m/Y",mktime());

    $month_given  = strtok($given_date, '/');
    $year_given = strtok('/');
    $month_now  = strtok($current_date, '/');
    $year_now = strtok('/');

    $diff_year = $year_given - $year_now;
    $diff_month = $month_given - $month_now;
    $our_diff = $diff_year * 12 + $diff_month;

    if($our_diff <= 6 && $our_diff >= 0){
      //less or equal than 6months
    }
    else if($our_diff > 6){
     //more than sixmonths
    }
    else{
    //negative number
    }