EDIT: @RiggsFolly helped with the problem, the format of the datetime i used was H:i:00 instead of H:i:s .
I need to compare the registration date and expiry date of a license, I stored both dates as strings in ssms, and I retrieve them as string, when I want to compare both, I tried converting both into DateTime objects so that I can compare them using date_diff()
, but for some reason I can only convert the expiry date into object, the registration date always returns boolean.
so the way my code works is, it firsts checks if the $expirydate
is empty, if not, then it will enter the condition and create $datetime
as a DateTime object, then create var $datetime1
to convert the $registrationdate
and store it, and create var $datetime2
to do the same for the $expirydate
. after that, if the dates are not returning false, then it will compare each other using date_diff()
, and then create var $validityperiod
to store the difference of days between the 2 dates in positive/negative integer, e.g. +30 or -3, it will be used to show the user how many days till their license expires.
I'm confused why both are string values but only one can be converted into DateTime object and the other returns boolean?
I tried 3 options to convert the DateTime string into DateTime object:
date_create()
but it also returns boolean, for both the registration and expiry date.date_create_from_format()
, same result as above, both returns boolean.create a
new DateTime()
object and usecreateFromFormat()
to convert it into DateTime object, but it only works on the expiry date and not the registration date, this is the closest I can get since it can at least convert the expiry date into a DateTime object.
//the string values from my db is:
// $registrationdate= "13/06/2019 15:06:06";
// $expirydate="14/06/2019 16:46:00";
//this example uses the third option
if ($expirydate != null || $expirydate != ''){
// creates DateTime objects
$datetime = new DateTime();
//the line below is the problem, it cant convert the string to object
$datetime1 = $datetime->createFromFormat('d/m/Y H:i:00', $registrationdate);
//however, this line below works, although both are strings
$datetime2 = $datetime->createFromFormat('d/m/Y H:i:00', $expirydate);
if ($datetime1!= false && $datetime2 != false){
// calculates the difference between DateTime objects
$interval = date_diff($datetime1, $datetime2);
// printing result in days format
$validityperiod= $interval->format('%r%a');
}
else $validityperiod = "";
}
every time when the conversion from string to object returns boolean, it returns the following error:
Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given
if it can convert the registration date to DateTime object, then it should be able to run the date_diff() and $validityperiod should store the difference of days between the 2 dates