Reputation: 415
I want to use timestamps.
I know that this outputs a timestamps:
$date = date_create();
echo date_format($date, 'U');
But I want to know how to make use of that time stamp. --> save it to a database, the later convert it to required timezone and then output it in the format that I choose.
I just don't know how to do that.
How can I use a time stamp?
Upvotes: 0
Views: 69
Reputation: 92785
Since your intent is just to store and then show your timestamps you can let mysql do the job.
Your table DDL might look like
CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`post` varchar(512) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Important part DEFAULT
CURRENT_TIMESTAMP
That way current timestamp will be assigned to post_date column on INSERT
INSERT INTO `posts` (`post`) VALUES ('post1');
Then you can use DATE_FORMAT
to fetch formatted timestamp data from mysql
SELECT id, DATE_FORMAT(post_date, '%m/%d/%Y %H:%i:%s') post_date, post
FROM `posts`
Output
+----+---------------------+-------+
| id | post_date | post |
+----+---------------------+-------+
| 1 | 02/20/2013 23:45:43 | post1 |
| 2 | 02/20/2013 23:45:43 | post2 |
+----+---------------------+-------+
But you if you want to format it in php you can use UNIX_TIMESTAMP()
in your query first
SELECT id, UNIX_TIMESTAMP(post_date) post_date, post FROM `posts`
and then format it with date()
like this, assuming that you fetched a row to $row
by your favorite extension (PDO or mysqli)
date_default_timezone_set('America/New_York');
echo date('m/d/Y H:i:s',$row['post_date']);
output
02/20/2013 23:45:43
Upvotes: 1