Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-25 11:31:14
Original
409 people have browsed it

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
Copy after login

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");
Copy after login

OOP Approach:

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template