PHP 5.2 -- Today's date - 7 days

Daniel Wilson
Daniel Wilson used Ask the Experts™
How do I say:
$StartDate = Today's Date - 7 Days
in PHP 5.2?

I've seen stuff where the date is decomposed into month, day, year, subtracted and re-assembled.  But that looks like August 5th - 7 days would come out to August -2nd ... which isn't really valid.

I was trying the DateTime::sub routine, but then found that my host is running 5.2, not 5.3.

I know this is a common need ... how is it done?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Unix timestamps are good for this.

$rightnowTimestamp = time();
$sevenDaysAgoTimestamp = $rightnowTimestamp - (7 * 86400); // there are 86400 seconds in a day
print date("m/d/Y",$sevenDaysAgoTimestaamp); // Turn the timestamp back into a formatted date
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009
strtotime function will make this easy:

echo strtotime("-1 week"), "\n";

Open in new window

Just FYI, the Unix timestamp is just the number of seconds since Jan 1st, 1970 at midnight (UTC timezone).

So if you ran:

print date("m/d/Y h:i:s A",0) . "\n";
print date("m/d/Y h:i:s A",86400) . "\n";
print date("m/d/Y h:i:s A",100000) . "\n";

You'd get:
01/01/1970 12:00:00 AM
01/02/1970 12:00:00 AM
01/02/1970 03:46:40 AM

(Note: This is assuming a UTC timezone, so there are no time offsets. If your server is in the U.S. and you don't change your timezone settings, then date-formatting a 0 timestamp might actually show 12/31/1969 because of the time difference).

So using timestamps, you can do a lot of easy date manipulation and have it be accurate down to the hour, minute, and second.


gr8gonzo, your code snippet worked great (once I corrected a little misspelling).  Thanks!

angelIII, yours gives me something funny ... but thanks for the shot at it!

Ah - sorry. My laptop keyboard at home sometimes repeats characters that I type.

angelll's suggestion technically works. It simply returned a unix timestamp. The strtotime() function takes a formatted date or English description of a date and changes it into a timestamp:

$januaryFirst2009Timestamp = strtotime("01/01/2009");
print date("m/d/Y",$januaryFirst2009Timestamp);

That code basically converts a date into a timestamp and then converts it back to the date again. Not really a useful piece of code, but it's a good illustration of converting back-and-forth between dates and timestamps.

Try date-formatting angelll's code:
echo date("m/d/Y",strtotime("-1 week"));

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial