将字符串转换为日期并在 php 中进行比较


Convert string to date and compare in php

我有一个字符串,想将其转换为日期,然后执行一些比较并执行一些操作。这是我的方案:

$a="2015-02-17" //yyyy-mm-dd
$b="2015-01-17" //yyyy-mm-dd
if ($a>$b)
{
//action1
}
else
{
//action2
}
$today = '2015-02-17';
$expire = '2015-01-01';
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) {
//do some thing
}

如果您使用的是 PHP 5>= 5.2.0,则可以使用 DateTime 类:

$date1 = new DateTime($today);
$date2 = new DateTime($expire);
if ($date1 < $date2) { /* Do something */ }