【问题标题】:filtering by date php for this month and last x days and this week按日期 php 过滤本月、最后 x 天和本周
【发布时间】:2012-09-14 12:21:26
【问题描述】:

我有一个日期以字符串形式返回 2012-03-19 05:00:32,它不是来自数据库

我可以在下面搜索过去 30 天

$date = '2012-03-19 05:00:32';
if (strtotime($date) >= strtotime('-7 days')) {
// do something
}

问题是如果今天是 3 月 19 日,我要从 11 日到 18 日搜索过去 7 天,这似乎是通过计算 24 小时 * 7 来搜索过去 7 天,我的搜索需要从每天 00:00:01。

我的计划是将日期分解为年、月和日,然后检查年 = 12,然后检查月 = 3,然后检查日期是否在 11 到 18 之间。

我只是想知道是否有更有效的方法可以做到这一点,或者我是否走在正确的轨道上。

我在搜索本月的所有信息时也遇到了同样的问题,并且还想从星期一开始搜索本周的所有信息。

所以这只是问我的方法是否合理,或者是否有更有效的方法。

【问题讨论】:

  • 检查您的时区在数据库中是否相同?

标签: php date time filter


【解决方案1】:
$mytime = new DateTime('2012-03-19 05:00:32');
$mydate = new DateTime($mytime->format('Y-m-d')); //keep date only, exclude the time component
$now=new DateTime; //includes hours, minutes, seconds
$today=new DateTime($now->format('Y-m-d')); //time set to 0:00

$interval = $mydate->diff($today);
if($interval->format('d') <=7) { //assuming that $mydate isn't in the past
 //do something
}

【讨论】:

    【解决方案2】:

    我建议使用DateTime class ...

    <?php
    $d1=new DateTime("2012-07-08 11:14:15.638276");
    $d2=new DateTime("2012-07-08 11:14:15.889342");
    $diff=$d2->diff($d1);
    print_r( $diff ) ;
    
    /* returns:
    
    DateInterval Object
    (
        [y] => 0
        [m] => 0
        [d] => 0
        [h] => 0
        [i] => 0
        [s] => 0
        [invert] => 0
        [days] => 0
    )
    
    */
    ?>
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多