Calculating and showing previous week's date

Hi, I’ve seen countless ways people suggest for doing this but none of them seem to do exactly what I want. Basically I have a date in a variable, picked using a date picker in a form, that then comes through to be used in a MySQL query.


$weekcommencing = '2013-11-04'; //for example

What I want is to also create a variable based on this that stores the equivalent value for the previous week, which in this case would be 2013-10-28.

I’ve tried using strtotime but it just outputs in seconds and I can’t see a way of making it display as the specified date.

I tried this:


$previousweek = strtotime ( "-1 week" , strtotime ( $weekcommencing ) ) ;

But if I echo it just returns some value in seconds.

I’m sure there must be a simple answer but can’t see what I need to do. Thanks.

“it just returns some value in seconds”. Well yes, strtotime returns seconds. Specifically, the timestamp (the “time” portion of the name [FPHP]strtotime[/FPHP]) of the specified date/time.

What you want to do is to reverse the process, which is the [FPHP]date/FPHP function. (and do a little bit of combining!)
date(‘Y-m-d’,strtotime($weekcommencing." -1 week"));

In conjunction with StarLion’s approach, here are a few more:

<?php
$weekcommencing = '2013-11-04'; //for example
var_dump(date('Y-m-d',strtotime($weekcommencing." -1 week")));

$weekcommencing = '2013-11-04'; //for example
$previousweek = getdate(strtotime("-1 week", strtotime($weekcommencing))) ;
var_dump($previousweek, sprintf('%4d-%2d-%2d', $previousweek['year'], $previousweek['mon'], $previousweek['mday']));

$weekcommencing = '2013-11-04'; //for example
$previousweek = new DateTime($weekcommencing);
$previousweek->sub(new DateInterval('P7D'));
var_dump($previousweek, $previousweek->format('Y-m-d'));

$weekcommencing = '2013-11-04'; //for example
$previousweek = new DateTime($weekcommencing);
$previousweek->sub(DateInterval::createFromDateString('1 week'));
var_dump($previousweek, $previousweek->format('Y-m-d'));