PHP strtotime Limitation
September 20, 2005
I have been relying very heavily on strtotime() in PHP in just about everything I write. For those not entirely familiar with this function, strtotime() will "parse about any English textual
Why create Unix date() date('m/d/Y'); will generate a reasonably nice US representation of today's date. However, if you did date('m/d/Y',strtotime('3 weeks ago')); you can get the nice readable format provided by date, but for some arbitrary date you are deciding upon with strtotime. Also, knowing strtotime happily accepts the date('m/d/Y',strtotime($row['date_field']));. For a complete list of the available date formats, visit
Ok, so the title of this makes reference to a limitation... on to that. On some
In the meantime, safestrtotime() function and shared it on PHP.net. I'm reproducing it here for my convenience, altered to match the code formatting I prefer.
-
<?php
-
-
function safestrtotime($strInput)
-
{
-
$iVal = -1;
-
for ($i=1900; $i<=1969; $i++)
-
{
-
// Check for this year string in date
-
$strYear = (string)$i;
-
{
-
$replYear = $strYear;
-
$yearSkew = 1970 - $i;
-
}
-
}
-
if ($yearSkew> 0)
-
{
-
$numSecs = (60 * 60 * 24 * 365 * $yearSkew);
-
$iVal = $iVal - $numSecs;
-
$numLeapYears = 0; // determine number of leap years in period
-
for ($j=$replYear; $j<=1969; $j++)
-
{
-
$thisYear = $j;
-
$isLeapYear = false;
-
// Is div by 4?
-
if (($thisYear % 4) == 0)
-
{
-
$isLeapYear = true;
-
}
-
// Is div by 100?
-
if (($thisYear % 100) == 0)
-
{
-
$isLeapYear = false;
-
}
-
// Is div by 1000?
-
if (($thisYear % 1000) == 0)
-
{
-
$isLeapYear = true;
-
}
-
if ($isLeapYear == true)
-
{
-
$numLeapYears++;
-
}
-
}
-
$iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
-
}
-
return $iVal;
-
}
-
?>
Tags: 1970-01-01, date format, datetime, Ed Lecky-Thompson, epoch, function, mysql, operating systems, PHP.net, timestamp, timestamps, Unix Epoch, Unix timestamp
Comments
5 Responses to “PHP strtotime Limitation”
Got something to say?

[...] Additionally, content has been categorized. Certain categories may contain more professional topics than others (for instance PHP, Identity Management, and Technology in general). Other categories such as Humor, Entertainment, Vacation and Travel, and General News are more likely to contain offensive or adult material. [...]
wow! this function was super helpful. thanks so much.
it gives error like this
Undefined variable: yearSkew in c:\inetpub\wwwroot\qcadmin\Untitled-1.php on line 18
That’s a PHP strict error, I have not initialized all variables in this script to be strict mode compatible…
When used in PHP on Windows, it displays:
Warning: date(): Windows does not support dates prior to midnight (00:00:00), January 1, 1970