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)

Belisarius Smith consults as a software engineer, cloud engineer, and security adviser. He has a BSBA in Security Management and is currently completing graduate studies in the Engineering Department at Penn State University with a Masters of Software Engineering. When he isn't traveling, mountain climbing, or reading, he spends his spare time on personal side projects and studies.

Leave a Reply