views:

1731

answers:

6

Is there anyone sitting on a PHP function to convert a date of format 0000-00-00 00:00:00(datetimesql) to unix timestamp?

Thanks in advance.

+1  A: 

Use strptime() to parse the time and turn it into a structured array.

Then pass the results of that into the mktime() function to get a UNIX timestamp.

Alnitak
Why is this voted down?
dalle
dunno - I'm 99% sure the question didn't mention SQL when I posted this answer
Alnitak
A: 

Try strptime.

dalle
+8  A: 

Another option as you have tagged this question with SQL: the MySQL functions FROM_UNIXTIME and UNIX_TIMESTAMP -> MySQL manual

SELECT UNIX_TIMESTAMP(datetime_column) FROM table

This usually is faster than a PHP function call.

wvanbergen
Why was this modded down? It's a perfectly good approach.
ceejayoz
I was asking myself the same question... :-) Always try to get the data out of the database as well as possible, as MySQL will always be faster than PHP.
wvanbergen
I don't think the SQL stuff was in the question when I downvoted this - maybe the edit was during the 5 minute window where it doesn't appear in the edit history? Down-vote reversed.
Alnitak
not that the user specified MySQL, and the UNIX_TIMESTAMP() function is not a standard SQL function...
Alnitak
Alnitak has a valid point, there are a lot of assumptions concerning whether a DB is involved or not wvanbergen. What if he's grabbing timestamps from filenames?
dcousineau
Timestamps from files already are in unix timestamp format when using PHP functions, the question is tagged SQL and the presented date format is exactly like MySQL returns datetime values. I am not saying this is the only options or the best option, just that it is another approach.
wvanbergen
+1  A: 

i think ill use http://php.net/strtotime
lol

Then vote the guy who answered your question as best answer, and post stuff like this in his answer's comments.
TravisO
+4  A: 

@bartek - As you noted, PHP's strtotime function is perfect for this. It can handle most common date formats, including strings like "tomorrow" or "+5 months".

ceejayoz
Note that because it can handle so many formats, it is really slow. Do not use it if you are going to call it often.
wvanbergen
Good point, thanks.
ceejayoz
yup, in fact the manual doesn't actually say whether this particular date-time format is supported. That's why I recommended strptime() instead.
Alnitak
SQL datetime formats are indeed supported in strtotime.
ceejayoz
+1  A: 

Encapusulating wvanbergen's solution into a function (for your convenience)

//Convert SQL datetime to unixtime -- by johnboiles
function datetimeToUnixtime($datetime){
    $result = mysql_query("select unix_timestamp('$datetime')");
    $unixtime = mysql_fetch_array($result);
    return $unixtime[0];
}
AlpacaJB