PHP日期比较问题

时间:2015-07-21 18:29:59

标签: php

我试图查看日期是否在当月的第一个和最后一个之间。我试图将以下$ dateInfo字符串转换为日期,因此我可以比较这些值...我怎样才能实现这一目标? DateInfo必须采用以下格式。

变量:

$dateInfo = '20150624T14:49:59'
$dFirst = new DateTime('first day of this month');
$dLast = new DateTime('last day of this month');

比较:

if(($dateInfo >= $dFirst) && (  $dateInfo<= $dLast )){
    echo 'something';}
}

4 个答案:

答案 0 :(得分:1)

尝试使用DateTime对象:

<?php
$dateInfo = new DateTime('20150724T14:49:59');
$dFirst = new DateTime('first day of this month');
$dLast = new DateTime('last day of this month');

if (($dateInfo >= $dFirst) && ($dateInfo <= $dLast)) {
    $string = "%s is between %s and %s";
    printf($string, $dateInfo->format('d/M/Y'), $dFirst->format('d/M/Y'), $dLast->format('d/M/Y'));
}

答案 1 :(得分:0)

试试这个:

$dateInfo = strtotime('20150624T14:49:59');
$dFirst = strtotime(date('01-m-Y')); // first day of month
$dLast = strtotime(date('Y-m-t'));  // last day of month

if(($dateInfo >= $dFirst) && (  $dateInfo<= $dLast )){
    echo 'something';}
}
祝你好运!

答案 2 :(得分:0)

$dateInfo = new DateTime('20150624T14:49:59');

这就形成了我的作品

答案 3 :(得分:0)

您可以将时间戳与DateTime::getTimestamp进行比较。

$dateInfo = '20150724T14:49:59';

$myDate = new DateTime($dateInfo);

$dFirst = new DateTime('first day of this month');
$dLast = new DateTime('last day of this month');

$occursThisMonth = $dFirst->getTimestamp() <= $myDate->getTimestamp() && 
                   $myDate->getTimestamp() <= $dLast->getTimestamp();