Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime exception and errors handling

Tags:

php

datetime

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?

like image 232
Saturnix Avatar asked Apr 15 '13 15:04

Saturnix


People also ask

What is exception and error handling in PHP?

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.

How do we use DateTime objects in PHP?

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.

What is new DateTime in PHP?

The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.

What are exceptions in PHP?

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.


2 Answers

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()

like image 168
faino Avatar answered Oct 14 '22 03:10

faino


strtotime() will return false if the format is bad so this should catch bad formats.

if (strtotime($in) === false)
{
     // bad format
}
like image 7
John Conde Avatar answered Oct 14 '22 01:10

John Conde