tags:

views:

87

answers:

3

Well, the following returns what date was 5 days ago:

$days_ago = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 5, date("Y")));

But, how do I find what was 5 days ago from any date, not just today?

For example: What was 5 days prior to 2008-12-02?

+3  A: 
define('SECONDS_PER_DAY', 86400);
$days_ago = date('Y-m-d', time() - 5 * SECONDS_PER_DAY);

Other than that, you can use strtotime for any date:

$days_ago = date('Y-m-d', strtotime('January 18, 2034') - 5 * SECONDS_PER_DAY);

Or, as you used, mktime:

$days_ago = date('Y-m-d', mktime(0, 0, 0, 12, 2, 2008) - 5 * SECONDS_PER_DAY);

Well, you get it. The key is to remove enough seconds from the timestamp.

zneak
Cool, but I have the date 2008-12-02 inside a variable $the_date. How to go about it, in this case?
Yeti
@Lost_in_code: you'd have used `strtotime` with it.
zneak
+3  A: 

I think a readable way of doing that is:

$days_ago = date('Y-m-d', strtotime('-5 days', strtotime('2008-12-02')));
Mike
This one works perfectly. Thanks!
Yeti
A: 

If you want a method in which you know the algorithm, or the functions mentioned in the previous answer aren't available: convert the date to Julian Day number (which is a way of counting days from January 1st, 4713 B.C), then subtract five, then convert back to calendar date (year, month, day). Sources of the algorithms for the two conversions is section 9 of http://www.hermetic.ch/cal_stud/jdn.htm or http://en.wikipedia.org/wiki/Julian_day

M. S. B.