Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strtotime for dates before 1970

Tags:

php

mysql

I have a text column in mysql and it stores a date value in the format yyyy-mm-dd. Now, in my php page, I use this code to parse into a date value.

date("F j, Y", strtotime($row['value']));

Now, I just read that strtotime() parses values only after January 1, 1970. I have lot of date values before that date. Is there a work around? I don't want to change my database structure.

like image 828
Ctroy Avatar asked May 20 '10 05:05

Ctroy


People also ask

How do I convert Strtotime to date format?

Code for converting a string to dateTime$date = strtotime ( $input ); echo date ( 'd/M/Y h:i:s' , $date );

Why is Strtotime return false?

strtotime expects a "English textual datetime" (according to the manual), which Y-D-M is not. Any time strtotime returns false, it simply doesn't understand your string, which in this application is expected.

Why is Strtotime used?

The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description.

How do you add a day in Strtotime?

echo date ( 'Y-m-d' , strtotime ( $Date . ' + 10 days' )); ?> Method 2: Using date_add() Function: The date_add() function is used to add days, months, years, hours, minutes and seconds.


1 Answers

From the documentation for strtotime():

strtotime() has a range limit between Fri, 13 Dec 1901 20:45:54 GMT and Tue, 19 Jan 2038 03:14:07 GMT; although prior to PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some operating systems (Windows).

What version of PHP are you running? And on what platform? Perhaps it's time for an upgrade.

If you're working with dates outside the 13 Dec 1901 to 19 Jan 2038 range, then consider using PHP's DateTime objects which can work with a much wider range of dates.

Procedural:

$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:

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

echo $date->format("F j, Y");
like image 185
Mark Baker Avatar answered Nov 02 '22 06:11

Mark Baker