Date Parsing in PHP
Date parsing is an essential function in PHP that allows users to convert a string representation of a date into a timestamp or a DateTime object. This function is useful in scenarios where dates are stored as strings, and it is necessary to perform date arithmetic or comparison operations. In this article, we will explore the various aspects of date parsing in PHP and provide a step-by-step guide to using the date_parse_from_format() function.
Understanding Date Parsing
Before we dive into the specifics of date parsing in PHP, it is important to understand what date parsing is and how it works. Date parsing refers to the process of extracting a date or time from a string representation of a date. For example, the string «2023-03-03» can be parsed into a timestamp or a DateTime object, which can then be used for various operations.
Date parsing can be challenging due to the various formats that dates can be represented in, such as «YYYY-MM-DD,» «MM/DD/YYYY,» «DD-MMM-YYYY,» and so on. To parse a date correctly, it is necessary to specify the format of the input string using a format string.
The date_parse_from_format() Function
In PHP, the date_parse_from_format() function is used to parse a date string using a specific format. This function returns an associative array containing detailed information about the parsed date, including the year, month, day, hour, minute, second, timezone, and more.
The syntax of the date_parse_from_format() function is as follows:
date_parse_from_format($format, $date_string);
Where $format is a string specifying the format of the input date string, and $date_string is the input date string that needs to be parsed.
Let’s take a look at an example:
$date_string = "2023-03-03 10:30:00"; $format = "Y-m-d H:i:s"; $date_array = date_parse_from_format($format, $date_string); print_r($date_array);
The output of this code will be:
Array ( [year] => 2023 [month] => 3 [day] => 3 [hour] => 10 [minute] => 30 [second] => 0 [fraction] => [warning_count] => 0 [warnings] => Array() [error_count] => 0 [errors] => Array() [is_localtime] => [zone_type] => 1 [zone] => -14400 [is_dst] => )
As you can see, the date_parse_from_format() function has successfully parsed the input date string «2023-03-03 10:30:00» using the format string «Y-m-d H:i:s.»
Using the date_parse_from_format() function, you can parse dates represented in various formats, including the day of the week, the month name, the AM/PM indicator, and more. You can also specify optional or alternative date and time formats using square brackets and the pipe symbol, respectively.
Conclusion
In conclusion, date parsing is an essential function in PHP that allows you to convert a string representation of a date into a timestamp or a DateTime object.
Php parsing string to date
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
date_parse_from_format
Returns associative array with detailed info about given date/time.
Parameters
Documentation on how the format is used, please refer to the documentation of DateTimeImmutable::createFromFormat() . The same rules apply.
String representing the date/time.
Return Values
Returns associative array with detailed info about given date/time.
The returned array has keys for year , month , day , hour , minute , second , fraction , and is_localtime .
If is_localtime is present then zone_type indicates the type of timezone. For type 1 (UTC offset) the zone , is_dst fields are added; for type 2 (abbreviation) the fields tz_abbr , is_dst are added; and for type 3 (timezone identifier) the tz_abbr , tz_id are added.
The array includes warning_count and warnings fields. The first one indicate how many warnings there were. The keys of elements warnings array indicate the position in the given datetime where the warning occurred, with the string value describing the warning itself. An example below shows such a warning.
The array also contains error_count and errors fields. The first one indicate how many errors were found. The keys of elements errors array indicate the position in the given datetime where the error occurred, with the string value describing the error itself. An example below shows such an error.
The number of array elements in the warnings and errors arrays might be less than warning_count or error_count if they occurred at the same position.
Changelog
Version | Description |
---|---|
7.2.0 | The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200 . |
Examples
Example #1 date_parse_from_format() example
The above example will output:
Array ( [year] => 2009 [month] => 1 [day] => 6 [hour] => 13 [minute] => 0 [second] => 0 [fraction] => [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => 1 [zone_type] => 1 [zone] => 3600 [is_dst] => )
Example #2 date_parse_from_format() with warnings example
$date = «26 August 2022 22:30 pm» ;
$parsed = date_parse_from_format ( «j F Y G:i a» , $date );
?php
echo «Warnings count: » , $parsed [ ‘warning_count’ ], «\n» ;
foreach ( $parsed [ ‘warnings’ ] as $position => $message ) echo «\tOn position < $position >: < $message >\n» ;
>
?>
The above example will output:
Warnings count: 1 On position 23: The parsed time was invalid
Example #3 date_parse_from_format() with errors example
$date = «26 August 2022 CEST» ;
$parsed = date_parse_from_format ( «j F Y H:i» , $date );
?php
echo «Errors count: » , $parsed [ ‘error_count’ ], «\n» ;
foreach ( $parsed [ ‘errors’ ] as $position => $message ) echo «\tOn position < $position >: < $message >\n» ;
>
?>
The above example will output:
Errors count: 3 On position 15: A two digit hour could not be found On position 19: Data missing
See Also
User Contributed Notes
- Date/Time Functions
- checkdate
- date_add
- date_create_from_format
- date_create_immutable_from_format
- date_create_immutable
- date_create
- date_date_set
- date_default_timezone_get
- date_default_timezone_set
- date_diff
- date_format
- date_get_last_errors
- date_interval_create_from_date_string
- date_interval_format
- date_isodate_set
- date_modify
- date_offset_get
- date_parse_from_format
- date_parse
- date_sub
- date_sun_info
- date_sunrise
- date_sunset
- date_time_set
- date_timestamp_get
- date_timestamp_set
- date_timezone_get
- date_timezone_set
- date
- getdate
- gettimeofday
- gmdate
- gmmktime
- gmstrftime
- idate
- localtime
- microtime
- mktime
- strftime
- strptime
- strtotime
- time
- timezone_abbreviations_list
- timezone_identifiers_list
- timezone_location_get
- timezone_name_from_abbr
- timezone_name_get
- timezone_offset_get
- timezone_open
- timezone_transitions_get
- timezone_version_get
Converting and Parsing a String into Date & Time
How to guess the date and time from a string with the help of strtotime() function and change the format according to your needs. You’ll also use the date_parse() and date_parse_from_format() functions which work similarly to the strtotime() function and return an associative array of date and time information.
Example: Guess date from a string and change its format
Example: Guess dates with strtotime() function
$format = 'd M Y'; echo 'Today: '. date($format).'
'; # Prints: Today: 09 Aug 2022 $yesterday = strtotime('Yesterday'); echo 'Yesterday: '. date($format, $yesterday) . '
'; # Prints: Yesterday: 08 Aug 2022 $tommorow = strtotime('Tomorrow'); echo 'Tomorrow: '. date($format, $tommorow). '
'; # Prints: Tomorrow: 10 Aug 2022 $lmonth = strtotime('Last Month'); echo 'Last month: '. date($format, $lmonth).'
'; # Prints: Last month: 09 Jul 2022 $nmonth = strtotime('Next Month'); echo 'Next month: '. date($format, $nmonth); # Prints: Last month: 09 Sep 2022The whole magic is put into the PHP function strtotime() , it parses about any English textual date/time description into a UNIX timestamp. The date() function reads the given timestamp and outputs a formatted date according to the provided format keywords.
date_parse()
Unlike the strtotime() function which converts a “date/time” string into timestamp, the date_parse() function converts a “date/time” string into an array describing that time and date. It returns false if it failed to parse the string.
int(1989) ["month"]=> int(8) ["day"]=> int(9) ["hour"]=> bool(false) ["minute"]=>bool(false) ["second"]=>bool(false) ["fraction"]=> bool(false) ["warning_count"]=> int(0) ["warnings"]=> array(0) < >["error_count"]=> int(0) ["errors"]=> array(0) < >["is_localtime"]=> bool(false) > */
date_parse_from_format()
This function parses a date/time string into an associative array representing a date/time. The string date/time is given in the format specified by $format parameter, using the same character codes as described in date() tutorial, see Date formattng symbols.
int(2022) ["month"]=> int(8) ["day"] => int(2) ["hour"] => int(17) ["minute"]=> int(1) ["second"]=> int(0) ["fraction"] => float(0) ["warning_count"]=> int(0) ["warnings"]=> array(0) < >["error_count"]=> int(0) ["errors"]=> array(0) < >["is_localtime"]=> bool(true) ["zone_type"]=> int(1) ["zone"] => int(7200) ["is_dst"] => bool(false) > */
The Date and Time Tutorials: