anjel
anjel

Reputation: 1382

extract time from date in php and store in mysql

I am making a request to twitter API and I want to extract the time from date in php and store in mysql..Does anyone know how to do that?

The time and date that i get from the results is this ...created_at": "Thu, 26 Jul 2012 22:16:59 +0000"

Thank you

Upvotes: 1

Views: 517

Answers (1)

Tadeck
Tadeck

Reputation: 137350

Storing timestamps in database

Use strtotime() on PHP side and FROM_UNIXTIME() on MySQL's side.

So basically your code, in short, may look like this:

$twitter_timestamp = 'Thu, 26 Jul 2012 22:16:59 +0000';
$php_time = strtotime($twitter_timestamp);
$query = 'INSERT INTO `some_table` VALUES ("' . $php_time . '");';

The above assumes you are storing the timestamp in the column with proper type (TIMESTAMP). To read more on differences between TIMESTAMP, DATE and DATETIME see this documentation page: MySQL Documentation: The DATE, DATETIME, and TIMESTAMP Types.

Storing time as string

If you want to store the timestamp in the way that is not timezone-aware (anything else than TIMESTAMP and not including timezone information), you will need to form the string representing your timestamp on the PHP side:

$twitter_timestamp = 'Thu, 26 Jul 2012 22:16:59 +0000';
$php_time = strtotime($twitter_timestamp);
// Optionally set local timezone:
date_default_timezone_set('America/Los_Angeles');
$php_timestamp = strftime('%T', $php_time); // will give "%H:%M:%S" timestamp
$query = 'INSERT INTO `some_table` VALUES ("' . $php_timestamp . '");';

Note, that date_default_timezone_set() call is optional - if you want the time in some specific timezone, different than current. The above assumes you want timestamp in the form of "HH:MM:SS".

Upvotes: 2

Related Questions