Hey!
I have heard lots of questions about how to display date from timestamp.
This is very simple. First we need to get a timestamp. You can get it from MySQL database if you have set your columns type to "time".
Or you can also get it from PHP's function called time();
It's time to create a function what will convert our timestamp to date.
Let's start!
1. Creating A Function
First we need to create a function:
PHP Code:
function getTime($timestamp) {
//.. Code here
}
So what have we done ?
function getTime($timestamp) { - This creates a new function called getTime(). As you can see there's a variable called $timestamp. It's for you so you can enter a timestamp to your function.
//.. Code here It is a PHP's comment. And this is the place where we will write our code
} Ends our function.
2. Let's Put It To Work
Now it's time to create a core for our function that will run it. Now remember to write code there were I showed you - inside those brackets.
First let's convert timestamp to date.
PHP Code:
$date = date("h:i:s jS F Y", $timestamp);
To read more about date(); function go here: http://ee.php.net/manual/en/function.date.php
As you can see I have added this $timestamp variable to that date function. This will tell to that function what timestamp to use instead of current timestamp.
And now we have to return a string of date.
Wasn't that easy.
Now let's see our full code:
PHP Code:
function getTime($timestamp) {
$date = date("h:i:s jS F Y", $timestamp);
echo $date;
}
You can also change this "h:i:s jS F Y" inside of date function. At the moment it shows "hours":"minutes":"seconds" "day as 12 + th or rd" "month as March" and "year as 2010"
For example:
PHP Code:
$time = "1267742730";
function getTime($timestamp) {
$date = date("h:i:s jS F Y", $timestamp);
echo $date;
}
getTime($time);
It shows this:
And this:
PHP Code:
<?php
$time = time(); // Get current UNIX timestamp
function getTime($timestamp) {
$date = date("h:i:s jS F Y", $timestamp);
echo $date;
}
getTime($time);
?>
And this displays the current time (at the moment - when I'm writing this tutorial):
I hope it helped you and I hope you enjoyed this tutorial.
Regards,
Jaan
Bookmarks