Rob
Rob

Reputation: 8101

Converting TIMESTAMP to unix time in PHP?

Currently I store the time in my database like so: 2010-05-17 19:13:37

However, I need to compare two times, and I feel it would be easier to do if it were a unix timestamp such as 1274119041. (These two times are different)

So how could I convert the timestamp to unix timestamp? Is there a simple php function for it?

Upvotes: 28

Views: 81189

Answers (5)

Florian Mertens
Florian Mertens

Reputation: 2448

Getting a unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);

Getting some mysql timestamp:

$mysqlTimestamp = '2013-01-10 12:13:37';

Converting it to a unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');

...comparing it with one or a range of times, to see if the user entered a realistic time:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}

Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

Upvotes: 7

ax.
ax.

Reputation: 59927

if you store the time in the database, why don't you let the database also give you the unix timestamp of it? see UNIX_TIMESTAMP(date), eg.

SELECT UNIX_TIMESTAMP(date) ...;

databases can also do date and time comparisons and arithmetic.

Upvotes: 2

webbiedave
webbiedave

Reputation: 48897

If you're using MySQL as your database, it can return date fields as unix timestamps with UNIX_TIMESTAMP:

SELECT UNIX_TIMESTAMP(my_datetime_field)

You can also do it on the PHP side with strtotime:

strtotime('2010-05-17 19:13:37');

Upvotes: 4

Matt
Matt

Reputation: 44058

You want strtotime:

print strtotime('2010-05-17 19:13:37'); // => 1274123617

Upvotes: 16

Mark
Mark

Reputation: 6254

You're looking for strtotime()

Upvotes: 41

Related Questions