I'm trying to create start and end dates using DateTime objects in PHP to perform some calculations. I currently generate the dates as follows:
$end = new DateTime(date("Y-m-t 23:59:59", strtotime("last month")));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));
What this will do is give me an end date of the final day of the previous month and a start date of the first day of the month six months prior to the end date. I've run some tests and this gives me the desired results of 2015-7-1
and 2015-12-31
. However, I've tried specifying different dates for the end date and receive erroneous results. Two particular examples are below:
$end = new DateTime(date("Y-m-t 23:59:59", strtotime("now")));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));
$end = new DateTime(date("Y-2-t 23:59:59"));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));
The first gives me a start date of 2015-7-1
yet again but correctly produces 2016-1-31
as the end date, and the second gives me a start date of 2015-9-1
and an end date of 2016-3-2
. What exactly am I doing wrong? I want these dates to be generated automatically, as per the first code segment.
Don't mix old and new functionality. You can simply use the interval method, like this:
$dt = new DateTime; // now
$dt->modify('+6 months'); // add 6 months to 'now'
echo $dt->format('Y-m-t');
$dt->modify('-7 hours');
echo $dt->format('Y-m-t');