PHP How to Convert String to Date Easily
new DateTime('your-string') or date('Y-m-d', strtotime('your-string')) to convert a string to a date in PHP.Examples
How to Think About It
Algorithm
Code
<?php $dateString = 'June 15, 2024'; $date = new DateTime($dateString); echo $date->format('Y-m-d H:i:s'); // Alternative using strtotime $timestamp = strtotime($dateString); echo "\n" . date('Y-m-d H:i:s', $timestamp); ?>
Dry Run
Let's trace converting 'June 15, 2024' to a date using DateTime and strtotime.
Create DateTime object
Input string: 'June 15, 2024' -> DateTime object representing 2024-06-15 00:00:00
Format DateTime
DateTime object formatted to 'Y-m-d H:i:s' -> '2024-06-15 00:00:00'
Use strtotime
strtotime('June 15, 2024') returns timestamp for 2024-06-15 00:00:00
Format timestamp
date('Y-m-d H:i:s', timestamp) -> '2024-06-15 00:00:00'
| Step | Action | Value |
|---|---|---|
| 1 | DateTime object created | 2024-06-15 00:00:00 |
| 2 | Formatted output | 2024-06-15 00:00:00 |
| 3 | Timestamp from strtotime | 1718448000 |
| 4 | Formatted date from timestamp | 2024-06-15 00:00:00 |
Why This Works
Step 1: Parsing the string
The DateTime constructor reads the string and converts it into a date object internally.
Step 2: Formatting the date
Using format() on the DateTime object outputs the date in a readable format like 'Y-m-d H:i:s'.
Step 3: Using strtotime
strtotime() converts the string to a Unix timestamp, which is a number representing seconds since 1970-01-01.
Step 4: Converting timestamp to date
The date() function formats the timestamp back into a human-readable date string.
Alternative Approaches
<?php $dateString = '15/06/2024'; $date = DateTime::createFromFormat('d/m/Y', $dateString); echo $date->format('Y-m-d'); ?>
<?php $dateString = '2024-06-15'; echo date('d-m-Y', strtotime($dateString)); ?>
Complexity: O(1) time, O(1) space
Time Complexity
Parsing a date string and formatting it is a constant time operation since it involves fixed steps without loops.
Space Complexity
Only a few variables and objects are created, so space usage is constant.
Which Approach is Fastest?
Using strtotime with date is slightly faster but less flexible than DateTime, which is better for complex formats and error handling.
| Approach | Time | Space | Best For |
|---|---|---|---|
| DateTime | O(1) | O(1) | Complex formats, error handling |
| strtotime + date | O(1) | O(1) | Simple, common formats |
| DateTime::createFromFormat | O(1) | O(1) | Known custom formats |
DateTime for more control and better error handling when converting strings to dates.