How can I prevent PHP to crash when creating a DateTime object?
$in = new DateTime($in);
$out = new DateTime($out);
$in
and $out
both comes from a form so they could be anything. I enforce the user to use a calendar and block it to dates with javascript. What if the user can bypass this check?
If $in = "anything else other than a date"
PHP will crash and block the rendering of the whole page.
How do I prevent this and just return(0)
if PHP is not able to parse the date?
With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
To use the DateTime object you just need to instantiate the the class. $date = new DateTime(); The constructor of this object takes two parameters the first is the time value you want to set the value of the object, you can use a date format, unix timestamp, a day interval or a day period.
The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.
An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.
Check out the documentation on DateTime()
, here's a little snippet:
<?php
try {
$date = new DateTime('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
echo $date->format('Y-m-d');
?>
PHP Manual DateTime::__construct()
strtotime()
will return false if the format is bad so this should catch bad formats.
if (strtotime($in) === false)
{
// bad format
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With