Home >Database >Mysql Tutorial >How Can I Handle Dates Before 1970 in PHP When Using `strtotime()`?

How Can I Handle Dates Before 1970 in PHP When Using `strtotime()`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 11:31:14470browse

How Can I Handle Dates Before 1970 in PHP When Using `strtotime()`?

Working with Dates Before 1970 Using strtotime()

Problem:

You have a text column in a MySQL database storing dates in the yyyy-mm-dd format. Your PHP code uses strtotime() to convert the dates, but you discover that it only parses values after January 1, 1970. Many of your dates fall before this limit, and you wonder if there's a workaround without altering your database structure.

Solution:

The official PHP documentation highlights the date range limitations of strtotime():

Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT

Option 1: Upgrade PHP Version and Operating System

If possible, upgrade to a PHP version equal to or greater than 5.1.0 on a platform that supports the extended date range.

Option 2: Utilize PHP's DateTime Objects

Consider using DateTime objects for dates outside the strtotime() range. They provide greater flexibility.

Procedural Approach:

$date = date_create($row['value']);
if (!$date) {
    $e = date_get_last_errors();
    foreach ($e['errors'] as $error) {
        echo "$error\n";
    }
    exit(1);
}

echo date_format($date, "F j, Y");

OOP Approach:

try {
    $date = new DateTime($row['value']);
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format("F j, Y");

The above is the detailed content of How Can I Handle Dates Before 1970 in PHP When Using `strtotime()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn