2013-03-11 140 views
-2

所以基本上,我想弄清楚如何在PHP中获得今天的日期。基本上我可以使用什么函数来获取它。PHP如果在今天的日期范围之前一周的条件

我试过以下内容:strtotime('now')但这给了我一个像这样的号码1362992653,我真的不能用。

我想以如下格式获得今天的日期20130311所以年/月/日这样我可以从它减去7。所以,我的if语句会是这个样子

$todaydate = some function; 
$mydate = 20130311 <-- will be in this format; 
$oneweekprior = $todaydate - 7; 

if ($mydate > $oneweekprior && $mydate < $todaysdate) { 

    then do my stuff; 

} 
+4

阅读'日期()'函数的文档。并且习惯于随时阅读文档。这个数字被称为UNIX时间戳,可以用来轻松地使用日期进行计算。 – kapa 2013-03-11 09:12:09

回答

3
$todayEpoch = strtotime(date('Y-m-d')); 
$mydate = strtotime('20130311'); 

$oneweekprior = $todayEpoch - 7*24*60*60; 

if ($mydate > $oneweekprior && $mydate < $todaysdate) { 

    then do my stuff; 

} 
2

这个数字你得到的,所谓的,UNIX时间戳 - 自01.01.1970秒和数量,主要是你应该用它来做些什么你想要做的事:

$todaydate = time(); // same as strtotime('now'), but without overhead of parsing 'now' 
$mydate = strtotime('20130311'); // turn your date into timestamp 
$oneweekprior = $todaydate - 7*24*60*60; // today - one week in seconds 
// or 
//$oneweekprior = strtotime('-7 days'); 

if ($mydate > $oneweekprior && $mydate < $todaysdate) { 
    // do something 
} 

把时间戳回人类可读的形式使用strftimedate功能:

echo strftime('%Y%m%d', $todaydate); 

,并请在PHP

阅读 documentation日期功能

的想法与比较日期时,您曾是非常糟糕的,让我们假设今天是20130301和日期检查是20130228 - 与您的解决方案将是:

$mydate = 20130228; 
$today = 20130301; 
$weekago = $today - 7; 

// $mydate should pass this test, but it won't because $weekago is equal 20130294 !! 
if ($mydate > $weekago && $mydate < $today) { 
} 
0

试试这个:

$now = time(); 

    $one_week_ago = $now - (60 * 60 * 24 * 7); 
    $date_today = date('Ymd', $now); 
    $date_week_ago = date('Ymd', $one_week_ago); 

    echo 'today: ' . $date_today . '<br /><br />'; 
    echo 'week-ago: ' . $date_week_ago . '<br /><br />'; 

从strtotime('now')得到的时间被称为从1970年1月1日以来的秒数。因此,time()会给你这个数字也是如此,然后你可以减去1周的价值秒,从而得到一周前的时间。

→有关日期()更多的信息,包括不同的字符串,如“年月日”的日期格式,请访问:http://php.net/manual/en/function.date.php

相关问题