[PHP] [TUT] An easy way to manipulate the date from a database

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
This is just a simply tutorial/guide on how to manipulate the date in PHP.

I'm not very good at explaining things, so I'm sorry if this doesn't make sense..

Have you ever wanted to display two formats of the date, but with the same date? I know it sounds confusing, but you will get what I mean in a bit..

Say the date is 13th April 2011, but you want to display it as:

13/04/2011
and
13th April 2011, 22:23 pm

But without saving multiple strings to a database and then calling them, well, an easier way to do it is to do this:

- in your database, add a field called 'timestamp' and save it as VARCHAR with a value of about 255 or something.
- run a similar code to this in your PHP:

PHP:
<?php
if( $_POST[submit] )
{
    $time = time();
    mysql_query( "INSERT INTO `posts` (`timestamp`) VALUES ('$time');" );
}
?>


- then in your code, do this:

PHP:
<?php
$query = mysql_query( "SELECT * FROM posts WHERE `id` = '1'" );
if( mysql_num_rows( $query) == 0 )
{
    echo "Doesn't exist!";
}
else
{
    $r = mysql_fetch_array( $query );
    $timestamp = $r["timestamp"]; //this will retrieve the value in the 'timestamp' column
    echo date( "F jS Y", $timestamp );
    echo "<br>";
    echo date( "F jS Y, g:i a", $timestamp );
}
?>

Now you're still probably thinking 'what the fuck', but this saves spaces in your code as you can use one string but manipulate it in different ways.

So basically all you have to do is add a 'timestamp' column and save 'time()' in it from PHP and then you can manipulate it when you retrieve it from the database.
 
Status
Not open for further replies.

Users who are viewing this thread

Top