php函数中的日期问题

时间:2014-01-03 00:27:24

标签: php

这是我的代码

   <?php
    $time = date("Y-m-d");

    $arr = file('logs/ban_list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $to_remove = $time;
    $arr = array_filter($arr, function($item) use ($to_remove) {
        return !preg_match("/$to_remove by /", $item);
    });
    file_put_contents('logs/ban_list.txt', join("\n", $arr));
    ?>

如何告诉脚本在当前日期之前删除任何内容以及任何内容?

问候格伦

编辑:新代码

<?php
$datetime = new DateTime(); 
$lastWeek = $datetime->sub(new DateInterval('P7D'));
$datetime->format('Y-m-d');
$arr = file('logs/ban_list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$to_remove = $datetime;
foreach ($to_remove as $item) {
    if ($to_remove->format('U') <= $datetime->format('U')) {
$arr = array_filter($arr, function($item) use ($to_remove) {
    return !preg_match("/$to_remove by /", $item);
});
file_put_contents('logs/ban_list.txt', join("\n", $arr));
    }
}
?>

收到此错误

Catchable fatal error: Object of class DateTime could not be converted to string in C:\xampp\htdocs\psys\logspeter\unban.php on line 10

1 个答案:

答案 0 :(得分:0)

我不知道您的整个设置,但这里有一个使用DateTime来比较日期的示例。

$now = new DateTime();
$lastWeek = $now->sub(new DateInterval('P7D'));

// Select your log items and get the date value out of it
foreach ($logitem as $item) {
    if ($to_remove_by->format('U') <= $now->format('U')) {
        // Remove - expiration date is behind us.
    }
}

这会抓住NOW时间,遍历每个项目并查看to_remove_by日期是否在我们后面。如果是这样,您可以安全地删除该项目。

->format('U')将日期转换为UNIX时间戳,以便更快地进行比较。