Code Snippets: PHP Function sqldate2timestamp

There are times when I have Dates variables which I’ve retrieved through SQL and they need manipulation sometimes later on in rare circumstances. In an environment where pulling too much data from the SQL DB (extra variations of a field) is bad, but pulling the data in its most basic form (timestamp from the start) costs too many CPU cycles (nobody ever said scripting languages were fast), a function like this comes in handy.

An example:

$my_ts = sqldate2timestamp($sql_date);
echo $my_ts;
1989348943830 (or whatever ;-)

Here’s the Code:

// FUNCTION: sqldate2timestamp
// ///////////////////////////////////////////////////////
// Description:
// This function takes an SQL date (e.g. 12/31/2001) and
// converts it into a timestamp.
// Note: None
// ///////////////////////////////////////////////////////
// Returns: long integer
function sqldate2timestamp($date)
    return mktime(1, 1, 1,
                  substr($date, 0, 2),
                  substr($date, 3, 2),
                  substr($date, 6, 4));

Disgustingly simple, but elegant at the same time. (Like all code should be IMHO)

Leave a Reply