user3189734
user3189734

Reputation: 665

PHP Date Intervals using date_add

I have the following code which works on the first 2 lines, taking my start date, converting to unix timestamp, and then adding one day.

The 3rd line is trying to use the value that is then generated to use the date interval to find the date in 2 months.

Unfortunately, the date_add seems to return the error 'date_add() expects parameter 1 to be DateTime, integer given'.

Can anyone tell me how I accomplish this using unix timestamp?

$startdate = strtotime('2014/12/19 15:00');
$weekstart = $startdate - (date("N",$startdate)*60*60*24)+(60*60*24);

$enddate = date_add($weekstart, DateInterval::createfromDateString('2 months'));

Upvotes: 0

Views: 891

Answers (2)

EternalHour
EternalHour

Reputation: 8621

Seems that you are wanting to create two different DateTime strings with different intervals. This should do it.

$startdate = new DateTime('2014/12/19 15:00');
$weekstart = $startdate->modify('+1 day');
$weekstart = $weekstart->format('U'); //change $weekstart to unix timestamp//

$enddate = $startdate->modify('+2 months');
$enddate = $enddate->format('U'); //change $enddate to unix timestamp//

Upvotes: 1

Marc B
Marc B

Reputation: 360672

So use a DateTime:

$startdate = new DateTime('2014/12/19 15:00');

internally DateTime's constructor will be using strtotime() anyways, giving you all the benefits (and risk) of strtotime()'s parsing logic, plus all the benefits of having the entire DateTime object available from the get-go.

The rest of your datemath can be accomplished using pure DateTime operations as well,w ithout having to do manual 60*60*24-type stuff.

Upvotes: 1

Related Questions