• PHP Video Tutorials

PHP date_get_last_errors() Function


Advertisements

Definition and Usage

The date_get_last_errors() is an alias of DateTime::getLastErrors()::__construct(). This function is used to get the warnings and errors occurred while parsing a date string.

Syntax

date_get_last_errors();

Parameters

This function doesn't accept any parameters

Return Values

PHP date_get_last_errors() function returns an array that contains all the warnings and errors that occur when you try to parse a date string.

PHP Version

This function was first introduced in PHP Version 5.5.0 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_get_last_errors() function −

<?php
   date_create("215-7896-848");
   $errors = date_get_last_errors();
   print_r($errors);
?>

This will produce following result −

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [8] => Double timezone specification
        )

    [error_count] => 5
    [errors] => Array
        (
            [0] => Unexpected character
            [1] => Unexpected character
            [2] => Unexpected character
            [6] => Unexpected character
            [7] => Unexpected character
        )

)

Example

Using this function you can catch the errors occurred while creating a date as shown below −

<?php
   try { 
      $res = new DateTime("215-7896-848");
      print($res);
   }  catch (Exception $e) { 
      print_r(DateTime::getLastErrors()); 
   }  
?>

This will produce following result −

Array
(
    [warning_count] => 1
    [warnings] => Array
        (
            [8] => Double timezone specification
        )

    [error_count] => 5
    [errors] => Array
        (
            [0] => Unexpected character
            [1] => Unexpected character
            [2] => Unexpected character
            [6] => Unexpected character
            [7] => Unexpected character
        )

)

Example

Following example displays the errors/warnings occurred while creating a DateTime object using the date_create_from_format() function −

//Creating a DateTime object
$date = "25-Mar-1989";
$format = "d-Z-Y";
$res = date_create_from_format($format, $date);
print_r(date_get_last_errors());

This will produce following result −

Array
(
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 3
    [errors] => Array
        (
            [3] => The format separator does not match
            [4] => Unexpected data found.
        )

)
php_function_reference.htm
Advertisements