Karol found a program that needs to look at a timestamp, and determine if that timestamp is before or after an expiration date. The code that was handling this looked like this:
public function _isSmsCodeExpired($id)
{
$genDateStr = $this->db()->query('SELECT date FROM table')->fetchColumn();
if (empty($genDateStr))
{
return true;
}
$expireDateArr = array();
$intervalSec = 120;
$genDataTmp = explode(' ', $genDateStr);
$genDataArr = explode('-', $genDataTmp[0]);
$expireDateArr['year'] = $genDataArr[0];
$expireDateArr['month'] = $genDataArr[1];
$expireDateArr['day'] = $genDataArr[2];
$genDataArr = explode(':', $genDataTmp[1]);
$expireDateArr['hour'] = $genDataArr[0];
$expireDateArr['minute'] = $genDataArr[1];
$expireDateArr['second'] = substr($genDataArr[2], 0, 2);
$intervalMin = (int) $intervalSec / 60;
$intervalSec = (int) $intervalSec - ( $intervalMin * 60 );
$expireDateArr['second'] += $intervalSec;
$expireDateArr['minute'] += $intervalMin;
$expireDateArr['second'] += $intervalSec;
if ($expireDateArr['second'] > 60)
{
$expireDateArr['minute'] += 1;
$expireDateArr['second'] = $expireDateArr['second'] - 60;
}
if ($expireDateArr['minute'] > 60)
{
$expireDateArr['hour'] += 1;
$expireDateArr['minute'] = $expireDateArr['minute'] - 60;
}
if ($expireDateArr['hour'] > 24)
{
$expireDateArr['day'] += 1;
$expireDateArr['hour'] = $expireDateArr['hour'] - 24;
}
$daysInMonth = date("t", strtotime($expireDateArr['year'] . "-" . $expireDateArr['month'] . "-01"));
if ($expireDateArr['day'] > $daysInMonth)
{
$expireDateArr['month'] += 1;
$expireDateArr['day'] = $expireDateArr['day'] - $daysInMonth;
}
if ($expireDateArr['month'] > 12)
{
$expireDateArr['year'] += 1;
}
$expireDate = new Zend_Date($expireDateArr);
$now = new Zend_Date();
if ($now->isEarlier($expireDate))
return false;
else
return true;
}
The real fun part of this was the choice to use Zend_Date
, which not only parses date strings, but also has built in methods to add seconds to a date. Of course, even that’s overkill
for solving this problem. Karol replaced most of the function with this:
return ((strtotime($genDateStr) + $intervalSec) > time()) ;
[Advertisement]
BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!