比较PHP上的两个日期,数据库上的日期格式为“2013年4月5日”


Comparing two dates on PHP when date format on Database is "Apr 5 2013"

大家好,我遇到了这个问题:我想擦除数据库中过去的记录。我只是想把月和日考虑进去。例如,如果数据库记录是(这是在DB上格式化的方式)"2013年4月5日"我需要与今天的日期"2013年4月6日"进行比较。在本例中,该记录被删除。我见过使用UNIX时间戳的例子,但没有一个使用日期('M j Y')的格式。谢谢!

在数据库中存储日期的较好方法是使用DATE或DATETIME格式。SQL允许您从这些类型中获取所需的所有信息。但是这样的请求应该可以工作。

你最终可以用正则表达式来做,但它会非常沉重…

但是你可以在PHP中做,得到所有的结果,然后浏览它们并使用strtotime之类的东西比较日期,然后删除每个ID。仍然非常繁重,但比在SQL请求中更容易实现。但是如果你能改变SQL架构,那就更好了。

我要尝试的方法是使用strtotime()将英文文本字符串转换为unix时间戳,然后将新时间戳与当前日期进行比较。下面是一些描述这种方法的php伪代码。

$threshold_to_deletion = numbers of days old a record is allowed to be;
$is_it_yesterday = 0;
$current_date = new DateTime();
$current_date->getTimestamp();
if ( !($is_it_yesterday = strtotime($str_from_db)) === false ) {
    $date_interval = date_diff($is_it_yesterday, $current_date);
    if( $date_interval >= $threshold_to_deletion ) {
        Do stuff here to delete
    }
} else {
    echo "DB string is not a valid date: $str_from_db";
} 

请注意,它没有完成或测试,它只是在那里松散地描述它将如何完成。我希望这对你有帮助。

Tim杜马斯

www.mpact-media.com