views:

46

answers:

3

I'm creating comments stored in a MySQL database.

I'm logging the php time function time() as the comment is posted. That way it's displaying a message such as... "comment... posted 4 seconds ago" and if I refresh the page 2 minutes later it'd display "comment... posted 2 minutes ago"

Here's how I am entering time() into the database along with the other data:

$date=time();

// Insert data into mysql
$sql="INSERT INTO testimonials (username, comment, date) 
  VALUES ('$username', '$comment', '$date')";

Now... I grab the data like this:

while ($row = mysql_fetch_row($result) )
{
  echo "<b>Random Comment</b></br>";
  echo ("<p>\n> $row[1]"); //comment
  echo ("</br>-$row[0]</p>"); //name
  echo ("</br>$row[2]"); //date

The sample output on my server is:

Random Comment

This is the most awesome comment thing ever!!!!

-Kyle

1278905319

How could I convert the time "1278905319" into a readable format such as, "posted 4 seconds ago" or something that deals with seconds, minutes, hours, days, weeks, months, years?

Is PHP the wrong way to do it? I read about MySQL timestamping but I don't understand that or how to make it work in my case.

So my main question is, how to format the time into a readable time on output. "2 seconds ago"

Thank you. =)

A: 

Here's a function I found here, written by one John McClumpha:

<?php
function RelativeTime($timestamp){
    $difference = time() - $timestamp;
    $periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");

    if ($difference > 0) { // this was in the past
        $ending = "ago";
    } else { // this was in the future
        $difference = -$difference;
        $ending = "to go";
    }       
    for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
    $difference = round($difference);
    if($difference != 1) $periods[$j].= "s";
    $text = "$difference $periods[$j] $ending";
    return $text;
}
amphetamachine
I'm not sure how to setup this to work with my table. I'm having trouble formatting my field."row[2]" How do I add "row[2]" into the $timestamp?
Ultima
Edit you know what I'm so blonde! I figured it out wow I'm dumb. Thank you for this answer this worked best!
Ultima
A: 

If you need complex time calculations, check out symfony's DateHelper, especially distance_of_time_in_words as found in the source. This is a very powerfull method does knows a very fine grained time calculation (e.g. 5 seconds ago, 20 seconds ago, about 1 minute ago, 10 minutes ago,...)


If you just want to have the date formatted, you can format it via MySQL:

SELECT your_fields, FROM_UNIXTIME(date, 'H:%i:%s') FROM table;

would give you 12:24:59 for example.

DrColossos
I don't need the date formatted in that format. I would like it such as the distance_of_time_in_words format. I just don't know how to go through the process from mysql into that function.How do I plugin the time table (row[2]) into that function so it outputs the complex time calculation?
Ultima
I figured it out thank you thank you. =)
Ultima
A: 

First, let MySQL insert the date for you by using an auto-updating timestamp field:

CREATE TABLE `table_a` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(255),
  `comment` TEXT,
  `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

This way, you don't need to worry about inserting the date from your PHP code, and if you do any testing from elsewhere - from the MySQL client, for instance, the date will still be inserted correctly.

You should also use the PHP DateTime Class (requires PHP 5.3.0 or greater), as it makes working with dates and times quite simple. Here's an example of getting some information from the database, and returning a formatted time interval:

$result = $mysqli->query(
    'SELECT ' .
    '`id`, ' .
    '`username`, ' .
    '`comment`, ' .
    '`date`, ' .
    'NOW(), ' .
    'FROM table');

$row = $result->fetch_assoc();

print_r($row);
Array
(
    [id] => 1
    [username] = 'Fred'
    [comment] = 'My first post'
    [date] => 2009-09-28 07:08:12
    [now] => 2010-07-12 08:47:03
)

$now = new DateTime($row['now']);
$post = new DateTime($row['date']);
$interval = $post->diff($now);
echo $interval->format('%m months, %d days, %d days, %h hours, %m minutes, %s seconds');

// 9 months, 14 days, 14 days, 1 hours, 9 minutes, 51 seconds

You can format the interval however you like using the DateInterval::format parameters. By getting MySQL to return NOW(), you ensure that any time discrepancy between your application server (the one running PHP), and your database server is avoided.

Mike
A subset of DateTime Class features were included in PHP5.1+ and they are good enough to do what Mike is suggesting. Another reason to use correct data fields in your database is that your table will make sense to you when you browse it with whatever you use to manage your database.
Cups
@Cups: I got the version information from the [DateInterval::format](http://uk3.php.net/manual/en/dateinterval.format.php) page. I wasn't aware that it was available in earlier versions. Thanks for the tip.
Mike