我正在逐行读取文本文件,每行都格式化为
05/20/2014 10:18:28 am
m/d/y h:m:s
如何将此与当前日期进行比较并选择不少于一周的日期? 这是我到目前为止所做的,但我想知道是否还有其他更简单的方法:
$arr = explode(' ',trim($line));
$fword = explode("/", $fword);
$fword = $arr[0];
list($m,$d,$y) = explode("/", $line);
mm= date('m');
dd = date('d');
顺便说一句,我正在以这种格式写文本文件:
$date = date('m/d/Y h:i:s a', time());
答案 0 :(得分:1)
您可以使用strtotime
。
$current_time = strtotime(date('d-M-Y g:i:s A'));
$one_week = 3600 * 24 * 7;
// your file code
$fword = $arr[0]; // assuming that $fword has file date.
// $fword = str_replace("/", "-", $fword);
$file_time = strtotime($fword);
$diff = $current_time - $file_time;
if($diff>$one_week)
{
echo " date : ".$fowrd." is older than one week <br/>";
}
else
{
echo " date : ".$fowrd." is not older than one week <br/>";
}
答案 1 :(得分:1)
忘记字符串操作和日期函数,改为使用DateTime类 - 它是为这类任务设计的。
//Current time
$now = new DateTimeImmutable();
//One week ago
$oneWeekAgo = $now->sub(new DateInterval('P1W'));
//Read whole file into array
$lines = file('test.txt', \FILE_SKIP_EMPTY_LINES | \FILE_IGNORE_NEW_LINES);
foreach ($lines AS $line) {
$date = DateTime::createFromFormat('m/d/Y h:i:s a+', $line);
//Here you can compare your dates like any other variables
if ($date > $oneWeekAgo) {
//Current date is less than 1 week "old"
}
if ($date < $oneWeekAgo) {
//Current date is more than 1 week "old"
}
}
对于不同的日期/时间段,请参阅http://www.php.net/manual/en/dateinterval.construct.php。例如,如果你想在&#34; 1天前和#34;做同样的事情,它将是 - &gt; sub(新的DateInterval(&#39; P1D&#39;)),&#34; 1未来一年&#34;将是 - &gt; add(new DateInterval(&#39; P1Y&#39;))。
答案 2 :(得分:0)
只需使用日期和strtotime方法
$t = '05/02/2014 10:18:28 am';
$aWeekLater = date('Y-m-d H:i:s', strtotime($t.' -1 week'));
$curDate = date('Y-m-d H:i:s');
if ($curDate < $aWeekLater) {
echo 'xxx';
} else {
echo 'yyy';
}
答案 3 :(得分:0)
if (60*60*24*7+time() < strtotime(trim($line))) {
// greater than 1 week in future
} else {
// within 1 week from now
}