简体   繁体   English

PHP日期比较问题

[英]PHP Date comparison issue

I am trying to see if a date is between the first and last of the current month. 我正在尝试查看日期是否在当前月份的第一天和最后一天之间。 I have tried to convert the following $dateInfo string to a date, so I can compare the values... How can I accomplish this? 我试图将下面的$ dateInfo字符串转换为日期,以便可以比较值...如何完成此操作? DateInfo has to be in the format below. DateInfo必须采用以下格式。

Variables: 变量:

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

The comparison: 比较:

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

Try using DateTime object: 尝试使用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'));
}

Try this: 尝试这个:

$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';}
}

Good luck! 祝好运!

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

这对我有效

You can compare timestamps with DateTime::getTimestamp . 您可以将时间戳与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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM