年动态转换为日期--- PHP

fkaflof6  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(105)

有谁知道如何在PHP中动态地将当前日期数据加载到日期中?例如:年,自动更新。我尝试了下面的方法,但没有成功。

$nowDate = date('d/m/Y');
$cYear = date('Y');             
$dateBegin = DateTime::createFromFormat('d/m/Y', '01/01/'.$cYear);
$dateEnd = DateTime::createFromFormat('d/m/Y', '31/12/'.$cYear);

if ($nowDate >= $dateBegin && $nowDate <= $dateEnd)
{
  echo "is between";
} else {
    echo 'OUT!';
}
qvtsj1bj

qvtsj1bj1#

您可以**比较DateTime对象:

$dateNow = new DateTime();          
$dateBegin = new DateTime($dateNow->format('Y-01-01 00:00:00'));
$dateEnd = new DateTime($dateNow->format('Y-12-31 23:59:59'));

if ($dateBegin <= $dateNow && $dateNow <= $dateEnd) {
  echo "is between";
} else {
    echo 'OUT!';
}

demo

9ceoxa92

9ceoxa922#

监视数据类型

string date ( string $format [, int $timestamp ] )
public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

做相同的类型和比较。

$nowDate = date('d/m/Y');
$cYear = date('Y');

$dateBegin = DateTime::createFromFormat('d/m/Y', '01/01/'.$cYear);
$dateEnd = DateTime::createFromFormat('d/m/Y', '31/12/'.$cYear);

// change to DateTime type
$nowDate2 = DateTime::createFromFormat('d/m/Y', $nowDate) ;
echo $nowDate2->format('Y-m-d')."\n";
echo $dateBegin->format('Y-m-d')."\n";
echo $dateEnd->format('Y-m-d')."\n";

if ($nowDate2 >= $dateBegin && $nowDate2 <= $dateEnd)
{
  echo "is between";
} else {
    echo 'OUT!';
}

相关问题