简体   繁体   中英

filtering by date php for this month and last x days and this week

I have a date that returns in a string as 2012-03-19 05:00:32, its not coming from the database

I can use below to search for the last 30 days

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

Problem is if today is the 19th March, i was to search from the 11th to the 18th for the last 7 days and that seems to search for the last 7 days by calculating 24 hours * 7 by my searches need to start from 00:00:01 each day.

My plan is to break the date down into Year, Month and Day then check if year = 12, then check if month = 3, then check if date between 11 and 18.

Im just wondering if there is a more efficient way to do this or if im on the right track.

I also have the same issue with running a search on all info from this month and also want to search for all info this week starting on Monday.

So this is just asking if my method is sound or if there is a more efficient method.

I'd suggest to use 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
)

*/
?>
$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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM