PHP: How to convert a string to date time

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Converting string formats into date and time objects is a frequent requirement in PHP development. This tutorial will explore various methods to achieve this, ensuring elegant and efficient data handling.

Using the strtotime() Function

The strtotime() function is the most straightforward way to convert a string into a Unix timestamp, which can then be formatted into a date and time. Here’s a basic example:

$dateString = '2023-03-15';
$timestamp = strtotime($dateString);
echo date('Y-m-d H:i:s', $timestamp);

This will output the formatted date and time based on the provided string.

Leveraging the DateTime Class

For more complexity and object-oriented approaches, the DateTime class comes in handy. The following snippet demonstrates its basic usage:

$dateString = 'next Thursday';
$dateTime = new DateTime($dateString);
echo $dateTime->format('Y-m-d H:i:s');

This will output the date and time for the next Thursday from the current date.

Dealing with Formats Using createFromFormat()

If you have a date string in a specific format, you can use the DateTime::createFromFormat() to convert it:

$dateString = '15-Mar-2023';
$dateTime = DateTime::createFromFormat('d-M-Y', $dateString);
echo $dateTime->format('Y-m-d');

This will display the date in the ‘Year-Month-Day’ format.

Handling Time Zones

Working with time zones is a common challenge. Here’s an example that demonstrates how to set a time zone while converting a string into a DateTime object:

$dateString = 'March 15, 2023, 12:00 PM';
$timeZone = new DateTimeZone('America/New_York');
$dateTime = new DateTime($dateString, $timeZone);
echo $dateTime->format('Y-m-d H:i:sP');

The output will be in the New York timezone with the offset included.

Advanced Parsing with IntlDateFormatter

For internationalization requirements, IntlDateFormatter can be used to convert strings according to locale. Below is an advanced example:

$dateString = '15 März 2023';
$formatter = new IntlDateFormatter('de_DE', IntlDateFormatter::FULL, IntlDateFormatter::FULL);
$timestamp = $formatter->parse($dateString);
echo date('Y-m-d', $timestamp);

This will output the date based on German locale settings.

Using Regex for Custom Parsing

Sometimes you need to handle dates in non-standard strings. Regular expressions can be used for custom parsing:

$dateString = 'Date: 2023/03/15, Time: 14:00';
preg_match('/Date: (\d{4}\/\d{2}\/\d{2}), Time: (\d{2}:\d{2})/', $dateString, $matches);
$dateTime = DateTime::createFromFormat('Y/m/d H:i', $matches[1] .' ' . $matches[2]);
echo $dateTime->format('Y-m-d H:i:s');

This uses regular expressions to extract the date and time from a string with a custom format.

Handling Exceptions and Errors

When conversion fails, it is essential to handle exceptions and errors gracefully. The following example demonstrates this:

try {
    $dateString = 'invalid date';
    $dateTime = new DateTime($dateString);
    echo $dateTime->format('Y-m-d H:i:s');
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

This will catch any exceptions that the DateTime class might throw due to invalid date strings.

Conclusion

In conclusion, PHP offers multiple ways to convert strings into date and time objects, catering to simple as well as complex requirements. Whether using basic functions or advanced classes, developers can handle various date string formats with the appropriate methods.