HKK
HKK

Reputation: 339

PHP add Months fails

i'm using

$membercontract_enddate = date('d.m.Y', strtotime("+'$months_o_duration' months", strtotime('$membercontract_startdate')));

$membercontract_startdate contains a timestamp for 9-Apr-2014

$months_o_duration contains the number of months, in my example 10,

$membercontract_enddate should be startdate plus months, in this cas 9-Feb-2015

But, actually, it always gets 01.01.1970. Why is that?

Upvotes: 0

Views: 59

Answers (2)

Othman
Othman

Reputation: 3018

strtotime will convert string to unix epoch. so the final result should be a string.

$membercontract_startdate = "09-Apr-2014";
$months_o_duration = 10;

$unix_start = strtotime($membercontract_startdate);
$months_o_duration_seconds = $months_o_duration * 30 * 24 * 60 * 60;
$unix_end = $unix_start + $months_o_duration_seconds;

$membercontract_enddate = date('d.m.Y', $unix_end);
echo $membercontract_enddate;

// out = 03.02.2015 // because of 30 days 

// in order to get 9-Feb-2015
$membercontract_startdate = "09-Apr-2014";
$unix_start = strtotime($membercontract_startdate, "+10 month");
$membercontract_enddate = date('d.m.Y', $unix_start);
echo $membercontract_enddate;

// out = 09.04.2014

You can do it in one line .. I am just explaining

Upvotes: 0

esqew
esqew

Reputation: 44701

Without seeing how you're actually declaring the rest of your variables, it looks to be most likely caused by your use of single quotes (') around your $membercontract_startdate reference - in PHP, variables in single quotes aren't interpreted.

For more information, the PHP Manual Strings page has information about the differences between single and double quotes.

Upvotes: 1

Related Questions