Reputation: 2103
I'm having problems with the handling of a date format. In my code, I try to calculate an expiration date starting from a specified date and then to save it in my MySQL database.
The problem is that I always receive this error:
Fatal error: Call to a member function add() on a non-object
and I'm not able to solve it. For example, it works if I manually replace $scadenza_contratto with a specific date, for example:
$expiration_date = DateTime::createFromFormat('Y-m-d', '2016-02-10');
In this case, it works, but I need to receive date from $scadenza_contratto. Can you help me, please? This is my code:
if($anno > 0 && $giorno > 0 && $mese >0){
$scadenza_contratto = $anno."-".$mese."-".$giorno;
//$scadenza_contratto = date('Y-m-d', strtotime("+{$scadenze} months", strtotime($scadenza_contratto)));
$sql1 = "SELECT * FROM scadenze WHERE contratto_id=$contratti_id";
$row1 = mysql_fetch_assoc( mysql_query($sql1) );
echo "tipo ".$row1['tipo'];
if(!$row1){
for ($m = $scadenze; $m <=60 ; $m += $scadenze){
//add $m to activation_date
$scadenza_contratto = $anno."-".$mese."-".$giorno;
$expiration_date = DateTime::createFromFormat('Y-m-d', '$scadenza_contratto');
$expiration_date->add(new DateInterval('P'.$m.'M'));
//do something with $expriration_date
echo "Expire: ".$expiration_date->format('Y-m-d'). "<br>";
$expiration_db = $expiration_date->format('Y-m-d H:i:s');
$time=time();
//mysql_query("INSERT INTO contratti (nome_area) VALUES('$nome_area','$giorno','$mese','$file_name','$attiva','$id_voce','$nome_azienda','$time')");
mysql_query("INSERT INTO scadenze (nome_azienda,nome_voce,contratto_id,nome_area,scadenza,tipo,created_date) VALUES ('$nome_azienda','$nome_voce','$contratti_id','$nome_area','$expiration_db','$scadenze','$time')");
}
}
}
Upvotes: 1
Views: 174
Reputation: 212422
First problem:
$expiration_date = DateTime::createFromFormat('Y-m-d', '$scadenza_contratto');
You're trying to convert the string literal '$scadenza_contratto'
to a date, rather than the value of the string variable $scadenza_contratto
.
A second problem is your format mask, as you're treating the values of $mese
and $giorno
as integers, then they may have values less than 10; and your current mask assumes that they will always be two digit values (with a leading 0
if less than 10), which may not be the case
Change this to
$expiration_date = DateTime::createFromFormat('Y-n-j', $scadenza_contratto);
Upvotes: 2