Thanks for posting the rest of the code, please refer to this fiddle
http://sandbox.onlinephpfunctions.com/code/78d2b6613dbadff5a79ab7ebed3cba304f1188fe
Here is the code
$DateTime = date_create_from_format('d M, h:i:s A ', $dateOfBoat);
$boatFinished = $DateTime->getTimestamp();
print_r("boatFinished: $boatFinished\n");
$now = time();
print_r("now: $now\n");
//Find interval between two dates
$interval = time()-$boatFinished;
print_r("Interval: $interval");
And the Output
boatFinished: 1514553217
now: 1509506464
Interval: -5046753
We can simplify things and take advantage of our DateTime
object. Because of that there is no need to output the date from the DateTime as a formatted string, and then convert that to a timestamp. We can instead get a timestamp directly from the dateTime object using it's getTimestamp()
method.
Once we have that as a unix timestamp, the rest is pretty trivial ( which you already had ). Get the current time time()
which is a timestamp. Then we just subtract them and we have the number of seconds between the two events.
You were very close.
UPDATE
Please refer to this second fiddle
http://sandbox.onlinephpfunctions.com/code/7d13d0319e266906df22624e701586914627f9dd
The first one is what I call a naive implementation, which just means that it does not consider enough edge cases. For this I would classify those as consiting of input other then we expect for the $dateOfBoat
variable. The main 2 I can think of are
- An empty input
- Input with an invalid format, or the completely wrong value
For both of these we can check if the DateTime
object was created using a simple Boolean comparison. After we try to create the DateTime, but before we use it we just need to add a simple condition, like this:
$DateTime = date_create_from_format('d M, h:i:s A ', $dateOfBoat);
if( !$DateTime ) //check that our DateTime object was properly created
throw new Exception("Invalid dateOfBoat input[{.$dateOfBoat}]");
$boatFinished = $DateTime->getTimestamp();
Here I am just throwing an Exception, It's up to you to decide how you want to handle this in your application. But raising an exception and handling it where this was called from, is certainly an option.
Cheers!