简体   繁体   中英

How can I get a period of time before date now in php?

I am trying to get a period of time with a date such as today is "2011-11-24" and I want to get 7 days before today:

The values would be :

"2011-11-23", "2011-11-22", "2011-11-21", "2011-11-20", 
"2011-11-19", "2011-11-18", "2011-11-17"

If I'm reading you right you want each of the previous seven days. Something like this would work:

$today = time();
for( $daysAgo = 1; $daysAgo <= 7; $daysAgo++ ) {
    echo date( 'Y-m-d', strtotime( "-$daysAgo days", $today ) ) . '<br />';
}
$timestamp = strtotime('YYYY-MM-DD - 1 week');

http://php.net/strtotime

Using the new date/time classes you can do the following:

$p = new DatePeriod(
    new DateTime('now'), 
    DateInterval::createFromDateString('-1 day'), 
    7, 
    DatePeriod::EXCLUDE_START_DATE
);
foreach ($p as $t) {
    echo $t->format('Y-m-d') . '<br />';
}

See DatePeriod , DateTime and DateInterval .

$timestamp = time() - (7*60*60*24);

echo date('Y-m-d',$timestamp);

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