function formatDate($datestr = '', $format = 'd M Y G:i')
{
    if ($datestr == '')
    {
        return FALSE;
    }

$datestr = trim($datestr);
$datestr = preg_replace("/\040+/", "\040", $datestr);

if ( ! ereg("^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}\040[0-9]{1,2}:[0-9]{1,2}.*$", $datestr))
{
    return FALSE;
}

$split = preg_split("/\040/", $datestr);

$ex = explode("-", $split['0']);            

$year  = (strlen($ex['0']) == 2) ? '20'.$ex['0'] : $ex['0'];
$month = (strlen($ex['1']) == 1) ? '0'.$ex['1']  : $ex['1'];
$day   = (strlen($ex['2']) == 1) ? '0'.$ex['2']  : $ex['2'];

$ex = explode(":", $split['1']); 

$hour = (strlen($ex['0']) == 1) ? '0'.$ex['0'] : $ex['0'];
$min  = (strlen($ex['1']) == 1) ? '0'.$ex['1'] : $ex['1'];

if (isset($ex['2']) AND ereg("[0-9]{1,2}", $ex['2']))
{
    $sec  = (strlen($ex['2']) == 1) ? '0'.$ex['2'] : $ex['2'];
}
else
{
    // Unless specified, seconds get set to zero.
    $sec = '00';
}

if (isset($split['2']))
{
    $ampm = strtolower($split['2']);

    if (substr($ampm, 0, 1) == 'p' AND $hour < 12)
        $hour = $hour + 12;

    if (substr($ampm, 0, 1) == 'a' AND $hour == 12)
        $hour =  '00';

    if (strlen($hour) == 1)
        $hour = '0'.$hour;
}

return date($format,mktime($hour, $min, $sec, $month, $day, $year));
} 

I have this function that I was given by a friend, I modified slightly (cant remember how much... i got it about a year ago). Anyway...

As the title of the subject suggests its to change a mySQL datetime string into a Unix timestamp so it can be used in the PHP date() function.

I was thinking it seemed like a very long winded way of doing it. Is there a better, neater, shorter solution?

Thanks

    How about

    strtotime( $date );
    

    As far as I know MySQL has a timestamp function too.

      My god. Didnt know mysql had a datestamp property available.

      Function added to the delte pile! 🙂

      Thanks lol.

        You could just use the UNIX_TIMESTAMP() function in MySQL:

        SELECT UNIX_TIMESTAMP(`date_col`) FROM `table_name`;
        

          You guys are making me feel stupid 😛 thats not fair... but thanks again.

          I never thought about it after i had been given the function... until now.

            Write a Reply...