Thursday, May 31, 2007

Php timestamp

I've been working with dates recently and today i became aware there are four methods to generate a timestamp.

echo time();
echo date('U');

These are the simplest functions. Then there is the mktime function which is the worst function of them all. The arguments are hour,minutes,seconds,month,day,year. I don't know which type of dateformat that should mirror but it's not a format i know of.

And then there is the most human accessible function strtotime. But there is one problem if you want the last day of the next month for example then you have to use strtotime two times.

My function combines mktime, time and strtotime functions into one and as an extra it's possible to have multiple strtotime strings in an array. Another extra is the possibility to change the timestamp output using the date function. The mktime function is accessed by a numeric value with the format yyyymmddhhmmss.

function tsgen($fromnow = '',$ts = '')
{
if($fromnow == '')
{
return ($ts == '')?time():date($ts);
}
else
{
if(is_array($fromnow))
{
$tempbegin = array_shift($fromnow);
$timestamp = strtotime($tempbegin);
if($timestamp == -1){ $timestamp = false; }
if (!$timestamp) {
return false;
}
else
{
$error = 0;
foreach($fromnow as $str)
{
$timestamp = strtotime($str,$timestamp);
if($timestamp == -1){ $timestamp = false; }
if (!$timestamp) { $error++; }
}
if($error > 0)
{
return false;
}
else
{
return ($ts == '')?$timestamp:date($ts,$timestamp);
}

}
}
else
{
if(is_numeric($fromnow) && strlen($fromnow) == 14)
{
return mktime(substr($fromnow,8,2), substr($fromnow,10,2), substr($fromnow,12,2), substr($fromnow,4,2), substr($fromnow,6,2), substr($fromnow,0,4));
}
else
{
$timestamp = strtotime($fromnow);
if($timestamp == -1){ $timestamp = false; }
if (!$timestamp) {
return false;
}
else
{
return ($ts == '')?$timestamp:date($ts,$timestamp);
}
}
}
}
}

Examples

echo tsgen();
echo tsgen('+1 day');
echo tsgen(20070101010101);
echo tsgen(array('+28 days','last friday'));
echo tsgen('next month','d-m-Y');

I hope people will enjoy using this unified timestamp/date function